Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
fix(release): externalize runtime assets and harden VT verification
Martin Vogel8018561cfe04
diff --git a/.github/workflows/_smoke.yml b/.github/workflows/_smoke.ymlindex 8a466ab57..d97969704 100644--- a/.github/workflows/_smoke.yml+++ b/.github/workflows/_smoke.yml@@ -206,8 +206,8 @@ jobs:mkdir -p "$ARTIFACT_DIR"unzip -o "codebase-memory-mcp${SUFFIX}-windows-${ARCH}.zip" -d "$ARTIFACT_DIR"test -s "$ARTIFACT_DIR/codebase-memory-mcp.exe"- # ONE binary per platform: a payload sibling would mean the- # AV-flagged launcher stub came back.+ # ONE executable per runtime set: a payload sibling would mean the+ # removed launcher split came back.test ! -e "$ARTIFACT_DIR/codebase-memory-mcp.payload.exe"# Pre-flight the image from a profile-rooted directory: the shared# runner workspace is deliberately not a valid install root.diff --git a/.github/workflows/_test.yml b/.github/workflows/_test.ymlindex 1223e194a..c6d98127b 100644--- a/.github/workflows/_test.yml+++ b/.github/workflows/_test.yml@@ -174,6 +174,37 @@ jobs:env:CCACHE_DIR: ${{ github.workspace }}/.ccache+ # The package wrappers own their own runtime-set publication and lease-lock+ # implementations. Run the same suites against both host families so Unix+ # inode/flock behavior and Windows handle/link behavior are each gating,+ # without adding Node/Go provisioning to every sanitizer/container leg.+ test-package-wrappers:+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, windows-latest]+ runs-on: ${{ matrix.os }}+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1++ - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0+ with:+ go-version-file: pkg/go/go.mod+ cache: false++ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: "22"++ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.12"++ - name: Test Go, npm, and PyPI runtime-set wrappers+ shell: bash+ run: scripts/ci/test-package-wrappers.sh+# ThreadSanitizer data-race gate. The threaded production surfaces (watcher,# subprocess, httpd, pipeline, mcp, worker pool, diagnostics, the runnable# daemon-coordination paths) plus allocator concurrency all run under TSan@@ -502,7 +533,7 @@ jobs:run: repo/scripts/ci/verify-shard-union.sh manifests# Windows product-surface regression guards. Distinct from test-windows above- # (the sanitizer C suite): these drive a real product binary + embedded HTTP UI+ # (the sanitizer C suite): these drive a real product binary + external UI pack# over stdio / CLI / HTTP and fail if a Windows bug already fixed on main comes# back -- non-ASCII repo paths dropping definitions (#636/#357, fixed by #700),# the PreToolUse hook augmenter no-op on drive-letter cwd (#618, fixed by #619),@@ -530,10 +561,6 @@ jobs:with:node-version: "22"- - name: Test npm wrapper failure handling- working-directory: pkg/npm- run: npm test-- name: Compiler cache (content-verified)uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0with:@@ -543,11 +570,12 @@ jobs:ccache-guards-${{ github.ref }}-ccache-guards-- - name: Build product binary with embedded UI+ - name: Build product binary with external UI assets and guard seamsshell: msys2 {0}- # --with-ui builds the frontend (npm) and embeds it, so the drive-picker- # guard's HTTP UI is available. Functional gate only (no sanitizers).- run: scripts/build.sh --with-ui CC=clang CXX=clang+++ # --with-ui builds the frontend and its content-addressed asset pack, so+ # the drive-picker guard's HTTP UI is available. Functional gate only+ # (no sanitizers).+ run: scripts/build.sh --with-ui CC=clang CXX=clang++ TEST_SEAMS=1env:CCACHE_DIR: ${{ github.workspace }}/.ccacheCCACHE_MAXSIZE: 1500Mdiff --git a/.github/workflows/dry-run.yml b/.github/workflows/dry-run.ymlindex bb0c51c71..19d6f4515 100644--- a/.github/workflows/dry-run.yml+++ b/.github/workflows/dry-run.yml@@ -149,22 +149,40 @@ jobs:# Same extraction the release verify job performs, so the bytes handed to# VirusTotal here are the bytes a user would download and run.- name: Extract archive artifacts- run: scripts/ci/extract-release-archives.sh assets binaries+ run: |+ scripts/ci/extract-release-archives.sh assets binaries \+ --expect-archives=16 \+ --expect-binaries=16 \+ --expect-packs=8 \+ --expect-runtime-files=64- name: VirusTotal scanuses: crazy-max/ghaction-virustotal@936d8c5c00afe97d3d9a1af26d017cfdf26800a2 # v5.0.0id: virustotalwith:vt_api_key: ${{ secrets.VIRUS_TOTAL_SCANNER_API_KEY }}- files: binaries/*+ files: binaries/objects/*+ request_rate: 4- # Same ZERO-tolerance gate as the release. A detection here is a real- # finding even when it is a false positive: it is what the release gate- # will do, so the dry run should say so now. Resolve it upstream (vendor- # false-positive submission for the exact hashes, then re-run) — never by- # loosening this gate.+ # Same ZERO-tolerance gate as the release. Every artifact must arrive+ # naturally clean; any malicious or suspicious verdict fails this run.- name: Wait for VirusTotal resultsenv:VT_API_KEY: ${{ secrets.VIRUS_TOTAL_SCANNER_API_KEY }}VT_ANALYSIS: ${{ steps.virustotal.outputs.analysis }}+ VT_EXPECTED_SCAN_SET: binaries/scan-set.tsv+ VT_ASSOCIATIONS: binaries/associations.tsv+ VT_RESULTS_PATH: binaries/vt-results.tsv+ MIN_ENGINES: 50run: scripts/ci/check-virustotal.sh++ - name: Preserve VirusTotal scope and result evidence+ if: ${{ always() }}+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: virustotal-evidence-dry-run-${{ github.run_id }}+ path: |+ binaries/associations.tsv+ binaries/scan-set.tsv+ binaries/vt-results.tsv+ if-no-files-found: warndiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 207c61cc6..b0c9ede3b 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -214,29 +214,21 @@ jobs:run: |mkdir -p assets binariesgh release download "$VERSION" --dir assets --repo "$GITHUB_REPOSITORY" --pattern '*.tar.gz' --pattern '*.zip'- for f in assets/*.tar.gz; do- NAME=$(basename "$f" .tar.gz)- tar -xzf "$f" -C binaries/ 2>/dev/null || true- [ -f binaries/codebase-memory-mcp ] && mv binaries/codebase-memory-mcp "binaries/${NAME}"- done- for f in assets/*.zip; do- NAME=$(basename "$f" .zip)- unzip -o "$f" -d binaries/ 2>/dev/null || true- [ -f binaries/codebase-memory-mcp.exe ] && mv binaries/codebase-memory-mcp.exe "binaries/${NAME}.exe"- done- cp install.sh binaries/ 2>/dev/null || true- cp install.ps1 binaries/ 2>/dev/null || true- ls -la binaries/+ scripts/ci/extract-release-archives.sh assets binaries \+ --expect-archives=16 \+ --expect-binaries=16 \+ --expect-packs=8 \+ --expect-runtime-files=64- - name: Security audits on all release files+ - name: Security audits on all unique release objectsrun: |- # Audit every file that ships in the release archives — binaries,- # install scripts, LICENSE, and any future companion files.+ # Audit every distinct archive/member/UI-asset byte sequence. The+ # associations manifest preserves every shipped archive location.# security-strings.sh detects file type and applies binary-only# rules (URL allowlist, dangerous-command detection) only to real# binaries; for shell scripts it still runs credential and base64# pattern audits.- for f in binaries/*; do+ for f in binaries/objects/*; do[ -f "$f" ] || continueecho "--- Auditing: $(basename "$f") ---"scripts/security-strings.sh "$f"@@ -247,24 +239,50 @@ jobs:id: virustotalwith:vt_api_key: ${{ secrets.VIRUS_TOTAL_SCANNER_API_KEY }}- files: binaries/*+ files: binaries/objects/*+ request_rate: 4- # ZERO tolerance: any detection on any artifact blocks the release.- # False positives are resolved upstream (Microsoft false-positive- # submission for the exact hashes, then re-run this job — no rebuild),- # never by loosening this gate.+ # ZERO tolerance: every artifact must arrive naturally clean. Any+ # malicious or suspicious verdict blocks the release with no exception.- name: Wait for VirusTotal resultsenv:VT_API_KEY: ${{ secrets.VIRUS_TOTAL_SCANNER_API_KEY }}VT_ANALYSIS: ${{ steps.virustotal.outputs.analysis }}+ VT_EXPECTED_SCAN_SET: binaries/scan-set.tsv+ VT_ASSOCIATIONS: binaries/associations.tsv+ VT_RESULTS_PATH: binaries/vt-results.tsv+ MIN_ENGINES: 50run: scripts/ci/check-virustotal.sh- # Renders per-binary sha256 + VT links into the notes; only reachable- # after the zero-tolerance gate passed, so "0 detections" is verified.+ - name: Preserve VirusTotal scope and result evidence+ if: ${{ always() }}+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: virustotal-evidence-release-${{ github.run_id }}+ path: |+ binaries/associations.tsv+ binaries/scan-set.tsv+ binaries/vt-results.tsv+ if-no-files-found: warn++ - name: Publish durable public VirusTotal evidence+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ VERSION: ${{ inputs.version }}+ VT_EXPECTED_SCAN_SET: binaries/scan-set.tsv+ VT_ASSOCIATIONS: binaries/associations.tsv+ VT_RESULTS_PATH: binaries/vt-results.tsv+ run: bash scripts/ci/publish-vt-evidence.sh++ # Renders the exact scan scope plus archive SHA-256/engine evidence. It+ # runs only after the exact-set zero-tolerance gate passed.- name: Append VirusTotal scan links to release notesenv:GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}VERSION: ${{ inputs.version }}+ VT_EXPECTED_SCAN_SET: binaries/scan-set.tsv+ VT_ASSOCIATIONS: binaries/associations.tsv+ VT_RESULTS_PATH: binaries/vt-results.tsvrun: bash scripts/ci/append-vt-notes.sh# ── 8. Publish package wrappers (npm + PyPI) ──────────────────diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.ymlindex 3db24d53c..aa91f91c3 100644--- a/.github/workflows/smoke.yml+++ b/.github/workflows/smoke.yml@@ -1,5 +1,6 @@-# Smoke invariants — "the shipped binary does not fail" — across the WIDEST set of-# GitHub-hosted runners. Builds the prod binary and runs scripts/smoke-invariants.sh+# Smoke invariants across the WIDEST set of GitHub-hosted runners. Builds the+# production source path with explicit fault-injection test seams and runs+# scripts/smoke-invariants.sh# (version/help, MCP initialize handshake [#513], all 14 tools invocable, malformed-# input resilience, clean EOF exit, shared-lib resolution, install dry-run).#@@ -54,8 +55,8 @@ jobs:- name: Install deps (Linux)if: startsWith(matrix.os, 'ubuntu')run: sudo apt-get update && sudo apt-get install -y zlib1g-dev python3 git- - name: Build (prod binary)- run: scripts/build.sh CC=${{ matrix.cc }} CXX=${{ matrix.cxx }}+ - name: Build (production path with explicit test seams)+ run: scripts/build.sh CC=${{ matrix.cc }} CXX=${{ matrix.cxx }} TEST_SEAMS=1- name: Smoke invariantsrun: |chmod +x scripts/smoke-invariants.sh@@ -82,9 +83,9 @@ jobs:makegitcoreutils- - name: Build (prod binary)+ - name: Build (production path with explicit test seams)shell: msys2 {0}- run: scripts/build.sh CC=clang CXX=clang+++ run: scripts/build.sh CC=clang CXX=clang++ TEST_SEAMS=1- name: Smoke invariantsshell: msys2 {0}run: |@@ -112,9 +113,9 @@ jobs:makegitcoreutils- - name: Build (prod binary)+ - name: Build (production path with explicit test seams)shell: msys2 {0}- run: scripts/build.sh CC=clang CXX=clang+++ run: scripts/build.sh CC=clang CXX=clang++ TEST_SEAMS=1- name: Smoke invariantsshell: msys2 {0}run: |diff --git a/Makefile.cbm b/Makefile.cbmindex f7eef1d78..a7c4b42b1 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -148,7 +148,7 @@ ifeq ($(IS_MINGW),yes)# two Windows builds of identical source are never byte-identical and every# release is a brand-new file to a reputation system. Same motivation as the# mimalloc __DATE__ patch; ELF and Mach-O have no equivalent field to clear.-WIN32_LIBS := -lws2_32 -lpsapi -lshell32 -ladvapi32 -Wl,--allow-multiple-definition -Wl,--stack,8388608 -Wl,--no-insert-timestamp -static+WIN32_LIBS := -lws2_32 -lpsapi -lshell32 -ladvapi32 -lbcrypt -Wl,--allow-multiple-definition -Wl,--stack,8388608 -Wl,--no-insert-timestamp -staticendif# STATIC=1 produces a fully static binary (for Alpine/musl portable builds)@@ -205,6 +205,7 @@ FOUNDATION_SRCS = \src/foundation/limits.c \src/foundation/subprocess.c \src/foundation/sha256.c \+ src/foundation/secure_random.c \src/foundation/macos_acl.c \src/foundation/private_file_lock.c \src/foundation/lock_registry.c@@ -254,7 +255,7 @@ TS_RUNTIME_DEPS = \$(wildcard $(CBM_DIR)/vendored/ts_runtime/src/portable/*.h) \$(wildcard $(CBM_DIR)/vendored/ts_runtime/src/unicode/*.h)-# All 64 grammar shim files+# All 159 grammar shim filesGRAMMAR_SRCS = $(wildcard $(CBM_DIR)/grammar_*.c)# LZ4 + Aho-Corasick@@ -359,13 +360,15 @@ CLI_SRCS = src/cli/cli.c src/cli/progress_sink.c src/cli/hook_augment.c src/cli/src/cli/config_json_like.c src/cli/config_toml_edit.c src/cli/config_yaml_edit.c \src/cli/config_text_edit.c src/cli/activation_transaction.c-# UI module (graph visualization)+# UI module (graph visualization). Production-standard builds deliberately link+# only the no-I/O pack stub. Test binaries substitute the real parser plus the+# empty manifest so parser/install behavior remains covered without a UI pack.UI_SRCS = \src/ui/config.c \src/ui/http_server.c \src/ui/layout3d.c \src/ui/httpd.c \- src/ui/embedded_stub.c+ src/ui/asset_pack_stub.c# mimalloc (vendored, global allocator override)#@@ -453,6 +456,7 @@ YYJSON_SRC = vendored/yyjson/yyjson.c# All production sourcesPROD_SRCS = $(FOUNDATION_SRCS) $(STORE_SRCS) $(CYPHER_SRCS) $(MCP_SRCS) $(DAEMON_SRCS) $(DISCOVER_SRCS) $(GRAPH_BUFFER_SRCS) $(PIPELINE_SRCS) $(SIMHASH_SRCS) $(SEMANTIC_SRCS) $(TRACES_SRCS) $(WATCHER_SRCS) $(GIT_SRCS) $(CLI_SRCS) $(UI_SRCS) $(YYJSON_SRC)+TEST_PROD_SRCS = $(subst src/ui/asset_pack_stub.c,src/ui/asset_pack.c src/ui/asset_manifest_stub.c,$(PROD_SRCS))EXISTING_C_SRCS = $(EXTRACTION_SRCS) $(LSP_SRCS) $(TS_RUNTIME_SRC) \$(GRAMMAR_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC)@@ -722,7 +726,7 @@ PP_OBJ_TSAN = $(BUILD_DIR)/tsan_preprocessor.o# ── Targets ──────────────────────────────────────────────────────-.PHONY: test test-par test-repro test-foundation test-tsan test-daemon-smoke cbm cbm-with-ui frontend embed clean-c lint lint-tidy lint-cppcheck lint-format security+.PHONY: test test-par test-repro test-foundation test-tsan test-daemon-smoke cbm cbm-with-ui frontend ui-pack clean-c lint lint-tidy lint-cppcheck lint-format security$(BUILD_DIR):mkdir -p $(BUILD_DIR)@@ -865,9 +869,9 @@ $(UNIXCODER_OBJ): $(UNIXCODER_BLOB_SRC) vendored/nomic/code_vectors.bin | $(BUILOBJS_VENDORED_TEST = $(MIMALLOC_OBJ_TEST) $(SQLITE3_OBJ_TEST) $(TRE_OBJ_TEST) $(GRAMMAR_OBJS_TEST) $(TS_RUNTIME_OBJ_TEST) $(LSP_OBJ_TEST) $(PP_OBJ_TEST) $(LZ4_OBJ_TEST) $(ZSTD_OBJ_TEST) $(UNIXCODER_OBJ)OBJS_VENDORED_TSAN = $(MIMALLOC_OBJ_TSAN) $(SQLITE3_OBJ_TSAN) $(TRE_OBJ_TSAN) $(GRAMMAR_OBJS_TSAN) $(TS_RUNTIME_OBJ_TSAN) $(LSP_OBJ_TSAN) $(PP_OBJ_TSAN) $(LZ4_OBJ_TSAN) $(ZSTD_OBJ_TSAN) $(UNIXCODER_OBJ)-$(BUILD_DIR)/test-runner: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR)+$(BUILD_DIR)/test-runner: $(ALL_TEST_SRCS) $(TEST_PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR)$(CC) $(CFLAGS_TEST) -Itests -Itests/repro -o $@ \- $(ALL_TEST_SRCS) $(PROD_SRCS) \+ $(ALL_TEST_SRCS) $(TEST_PROD_SRCS) \$(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \$(OBJS_VENDORED_TEST) \$(LDFLAGS_TEST)@@ -893,9 +897,9 @@ test-focused: $(BUILD_DIR)/test-runner# Mirrors test-runner's link line but uses repro_main.c (own main + counters)# and TEST_REPRO_SRCS instead of ALL_TEST_SRCS. Exits non-zero while any bug is# still reproduced (the expected state); bug-repro.yml surfaces it as a board.-$(BUILD_DIR)/test-repro-runner: $(TEST_REPRO_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR)+$(BUILD_DIR)/test-repro-runner: $(TEST_REPRO_SRCS) $(TEST_PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TEST) $(PROJECT_HDRS) | $(BUILD_DIR)$(CC) $(CFLAGS_TEST) -Itests -o $@ \- $(TEST_REPRO_SRCS) $(PROD_SRCS) \+ $(TEST_REPRO_SRCS) $(TEST_PROD_SRCS) \$(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \$(OBJS_VENDORED_TEST) \$(LDFLAGS_TEST)@@ -953,9 +957,9 @@ TSAN_OPTIONS ?= halt_on_error=1:report_thread_leaks=0# Normal ASan/native/soak paths remain uncapped. High-worker TSan diagnostics# invoke test-runner-tsan directly so release gates cannot drift accidentally.-$(BUILD_DIR)/test-runner-tsan: $(ALL_TEST_SRCS) $(PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR)+$(BUILD_DIR)/test-runner-tsan: $(ALL_TEST_SRCS) $(TEST_PROD_SRCS) $(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) $(OBJS_VENDORED_TSAN) $(PROJECT_HDRS) | $(BUILD_DIR)$(CC) $(CFLAGS_TSAN) -Itests -Itests/repro -o $@ \- $(ALL_TEST_SRCS) $(PROD_SRCS) \+ $(ALL_TEST_SRCS) $(TEST_PROD_SRCS) \$(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \$(OBJS_VENDORED_TSAN) \$(LDFLAGS_TSAN)@@ -1042,33 +1046,40 @@ $(BUILD_DIR)/codebase-memory-mcp: $(MAIN_SRC) $(PROD_SRCS) $(EXTRACTION_SRCS) $(cbm: $(BUILD_DIR)/codebase-memory-mcp@echo "Built: $(BUILD_DIR)/codebase-memory-mcp"-# ── Build with embedded UI (requires Node.js) ───────────────────+# ── Build with external UI asset pack (requires Node.js) ────────-# Swap embedded_stub.c for the generated embedded_assets.c-UI_SRCS_WITH_ASSETS = $(subst src/ui/embedded_stub.c,src/ui/embedded_assets.c,$(UI_SRCS))-PROD_SRCS_WITH_ASSETS = $(subst src/ui/embedded_stub.c,src/ui/embedded_assets.c,$(PROD_SRCS))--# Embedded asset object files (generated by embed script)-EMBED_OBJS = $(wildcard $(BUILD_DIR)/embedded/embed_*.o)+# The native image contains only a generated manifest (pack basename, SHA-256+# and byte length). Frontend bytes stay in a content-addressed sidecar next to+# the binary so release scanners can inspect them independently.+UI_ASSET_MANIFEST = $(BUILD_DIR)/generated/ui_asset_manifest.c+UI_ASSET_DIST ?= graph-ui/dist+UI_ASSET_PREBUILT ?= 0+ifeq ($(UI_ASSET_PREBUILT),1)+UI_ASSET_BUILD_PREREQ :=+else+UI_ASSET_BUILD_PREREQ := frontend+endif+PROD_SRCS_WITH_ASSETS = $(subst src/ui/asset_pack_stub.c,src/ui/asset_pack.c $(UI_ASSET_MANIFEST),$(PROD_SRCS))frontend:cd graph-ui && npm ci && npm run build-embed: frontend- scripts/embed-frontend.sh graph-ui/dist $(BUILD_DIR)/embedded+$(UI_ASSET_MANIFEST): $(UI_ASSET_BUILD_PREREQ) scripts/pack-ui-assets.mjs | $(BUILD_DIR)+ node scripts/pack-ui-assets.mjs $(UI_ASSET_DIST) $(BUILD_DIR) $@++ui-pack: $(UI_ASSET_MANIFEST)# $(INTEGRATIONS_HASH_HDR): generated header included by integration_assets.c.# The standard target gets it via $(PROJECT_HDRS); the UI target compiles in one# shot and must list it too, or the build fails with "cbm_integrations_hash.h# file not found" (seen on the Windows UI build).-cbm-with-ui: embed $(INTEGRATIONS_HASH_HDR) $(OBJS_VENDORED_PROD)+cbm-with-ui: ui-pack $(INTEGRATIONS_HASH_HDR) $(OBJS_VENDORED_PROD)$(CC) $(CFLAGS_PROD) -o $(BUILD_DIR)/codebase-memory-mcp \$(MAIN_SRC) $(PROD_SRCS_WITH_ASSETS) \$(EXTRACTION_SRCS) $(AC_LZ4_SRCS) $(ZSTD_SRCS) $(SQLITE_WRITER_SRC) \$(OBJS_VENDORED_PROD) \- $(wildcard $(BUILD_DIR)/embedded/embed_*.o) \$(LDFLAGS)- @echo "Built with UI: $(BUILD_DIR)/codebase-memory-mcp"+ @echo "Built with UI asset pack: $(BUILD_DIR)/codebase-memory-mcp"clean-c: export BUILD_DIR := $(BUILD_DIR)clean-c:diff --git a/README.md b/README.mdindex 926d13d7b..203d6f1c9 100644--- a/README.md+++ b/README.md@@ -7,20 +7,20 @@[](https://github.com/DeusData/codebase-memory-mcp)[](#hybrid-lsp)[](https://github.com/DeusData/codebase-memory-mcp)-[](https://github.com/DeusData/codebase-memory-mcp)+[](https://github.com/DeusData/codebase-memory-mcp)[](https://github.com/DeusData/codebase-memory-mcp/releases/latest)[](https://scorecard.dev/viewer/?uri=github.com/DeusData/codebase-memory-mcp)[](https://slsa.dev)[](https://github.com/DeusData/codebase-memory-mcp/releases/latest)[](https://arxiv.org/abs/2603.27277)-**The fastest and most efficient code intelligence engine for AI coding agents.** Full-indexes an average repository in milliseconds, the Linux kernel (28M LOC, 75K files) in 3 minutes. Answers structural queries in under 1ms. Ships as a single static binary for macOS, Linux, and Windows — download, run `install`, done.+**The fastest and most efficient code intelligence engine for AI coding agents.** Full-indexes an average repository in milliseconds, the Linux kernel (28M LOC, 75K files) in 3 minutes. Answers structural queries in under 1ms. Ships as a native executable with a small verified runtime-asset set for macOS, Linux, and Windows — download, run `install`, done.-High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-sitter/) AST analysis across all 158 languages, enhanced with [**Hybrid LSP** semantic type resolution](#hybrid-lsp) for Python, TypeScript / JavaScript / JSX / TSX, PHP, C#, Go, C, C++, Java, Kotlin, Rust, and Perl — producing a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. 15 MCP tools. Zero dependencies. Plug and play across 43 supported automatic/conditional client surfaces.+High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-sitter/) AST analysis across all 158 languages, enhanced with [**Hybrid LSP** semantic type resolution](#hybrid-lsp) for Python, TypeScript / JavaScript / JSX / TSX, PHP, C#, Go, C, C++, Java, Kotlin, Rust, and Perl — producing a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. 15 MCP tools. No language runtime, hosted service, or API key. Plug and play across 43 supported automatic/conditional client surfaces.> **Research** — The design and benchmarks behind this project are described in the preprint [*Codebase-Memory: Tree-Sitter-Based Knowledge Graphs for LLM Code Exploration via MCP*](https://arxiv.org/abs/2603.27277) (arXiv:2603.27277). Evaluated across 31 real-world repositories: 83% answer quality, 10× fewer tokens, 2.1× fewer tool calls vs. file-by-file exploration.-> **Security & Trust** — This tool reads your codebase and writes to your agent configuration files. That is what it is designed to do. If you prefer to audit before running, the [full source is here](https://github.com/DeusData/codebase-memory-mcp) — every release binary is signed, checksummed, and scanned by 70+ antivirus engines. All processing happens 100% locally; your code never leaves your machine. Found a security issue? We want to know — see [SECURITY.md](SECURITY.md). Security is Priority #1 for us.+> **Security & Trust** — This tool reads your codebase and writes to your agent configuration files. That is what it is designed to do. If you prefer to audit before running, the [full source is here](https://github.com/DeusData/codebase-memory-mcp). Release archives are signed and checksummed; every distinct shipped archive, member, and UI-asset byte object is submitted to VirusTotal. The release notes record the measured engine count and exact 0/N result; publication requires at least 50 decisive engine results with zero malicious and zero suspicious verdicts. All processing happens 100% locally; your code never leaves your machine. Found a security issue? We want to know — see [SECURITY.md](SECURITY.md). Security is Priority #1 for us.<p align="center"><img src="docs/graph-ui-screenshot.png" alt="Graph visualization UI showing the codebase-memory-mcp knowledge graph" width="800">@@ -31,7 +31,7 @@ High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-si## Why codebase-memory-mcp- **Extreme indexing speed** — Linux kernel (28M LOC, 75K files) in 3 minutes. RAM-first pipeline: LZ4 compression, in-memory SQLite, fused Aho-Corasick pattern matching. Memory released after indexing.-- **Plug and play** — single static binary for macOS (arm64/amd64), Linux (arm64/amd64), and Windows (amd64). No Docker, no runtime dependencies, no API keys. Download → `install` → restart agent → done.+- **Plug and play** — native executable plus authenticated release-owned assets for macOS (arm64/amd64), Linux (arm64/amd64), and Windows (amd64). The native install needs no Docker, language runtime, or API keys. Download → `install` → restart agent → done.- **158 languages** — vendored tree-sitter grammars compiled into the binary. Nothing to install, nothing that breaks.- **120x fewer tokens** — 5 structural queries: ~3,400 tokens vs ~412,000 via file-by-file search. One graph query replaces dozens of grep/read cycles.- **43 supported automatic/conditional client surfaces** — `install` configures detected clients and safely activates conditional clients only when their documented platform, marker, or explicit existing config path is present. See [Multi-Agent Support](#multi-agent-support) for the complete matrix and manual/UI-only boundaries.@@ -120,17 +120,18 @@ All active CBM processes must run the exact same version, executable build, coorThe native `install`, `update`, and `uninstall` commands are the deliberate exception to that conflict rule. Download, verification, and private same-filesystem staging happen first so a bad candidate never disrupts active work. Activation then publishes account-wide maintenance intent, asks the daemon and every temporary local operation to cancel, and waits to a finite deadline for all coordinated CBM processes to exit. It holds the admission and lifetime barriers exclusively while changing the active binary, configuration, PATH, or indexes. New CBM work cannot enter during this window. Activation progress and results are recorded in `${CBM_CACHE_DIR}/logs/activation-events.ndjson`, and a successful command tells you to restart open coding-agent sessions so they launch the activated build.-Package-manager setup (npm, PyPI, or Go) only verifies and atomically publishes that package's private cached binary; it does not replace the active native installation and therefore does not stop running CBM sessions. When that cached binary is executed, it still enters the same exact-build admission barrier. The shell and PowerShell installers invoke the verified candidate's native `install` command, so they do receive the full account-wide activation guarantee.+Package-manager setup (npm, PyPI, or Go) verifies and publishes a coherent private cached runtime set. Sidecars are replaced before the executable with per-file atomic renames; an interrupted multi-file publication is detected and repaired on the next launch rather than being described as one crash-atomic filesystem transaction. It does not replace the active native installation and therefore does not stop running CBM sessions. When that cached binary is executed, it still enters the same exact-build admission barrier. The shell and PowerShell installers invoke the verified candidate's native `install` command, so they do receive the full account-wide activation guarantee.The ordinary `cli` mode is intentionally separate: it runs one command locally and never starts or connects to the coordination daemon, registers a daemon session, or starts watchers/UI. Its only shared state is the OS admission barrier plus per-project locks for graph mutations. While the command is running, a temporary monitor lets activation cancel that operation and its supervised worker safely; the monitor exits with the command and never becomes a standing daemon. See [CLI Mode](#cli-mode) for details.### Graph Visualization UI-The UI ships as a separate `ui` build (it embeds the frontend). The default install on every channel is the lean, headless server; opt into the UI build with:+The UI currently ships as a separate `ui` build whose executable embeds only a content-addressed manifest; the deterministic frontend pack is a verified sidecar beside it. The default install on every channel is the lean, headless server; opt into the UI build with:- **install.sh:** add `--ui` (see [Quick Start](#quick-start))- **npm:** `CBM_VARIANT=ui npm install -g codebase-memory-mcp`- **PyPI:** `CBM_VARIANT=ui pip install codebase-memory-mcp`+- **Go:** after `go install github.com/DeusData/codebase-memory-mcp/pkg/go/cmd/codebase-memory-mcp@latest`, run the wrapper with `CBM_VARIANT=ui`- **Manual:** download the `codebase-memory-mcp-ui-<os>-<arch>` archiveThen run it:@@ -231,7 +232,7 @@ The install script placed beside the binary is **reported, not deleted** — uni- **RAM-first pipeline**: LZ4 compression, in-memory SQLite, single dump at end. Memory released after.### Distribution & operation-- **Single static binary, zero infrastructure**: SQLite-backed, persists to `~/.cache/codebase-memory-mcp/`+- **Native runtime set, zero infrastructure services**: SQLite-backed, persists to `~/.cache/codebase-memory-mcp/`- **Auto-sync**: Background watcher detects file changes and re-indexes automatically- **Route nodes**: REST endpoints are first-class graph entities- **CLI mode**: `codebase-memory-mcp cli search_graph '{"project": "my-project", "name_pattern": ".*Handler.*"}'`@@ -318,7 +319,7 @@ When you open a memory/performance issue, **attach the `.ndjson` trajectory**| Linux (ARM64) | `codebase-memory-mcp-linux-arm64.tar.gz` | `codebase-memory-mcp-ui-linux-arm64.tar.gz` || Windows (x86_64) | `codebase-memory-mcp-windows-amd64.zip` | `codebase-memory-mcp-ui-windows-amd64.zip` |-Every release includes `checksums.txt` with SHA-256 hashes. All binaries are statically linked — no shared library dependencies.+Every release includes `checksums.txt` with SHA-256 hashes. Keep the native executable together with the authenticated `cbm-integrations.json` asset and, for the UI variant, its single content-addressed `cbm-ui-<sha256>.pack`. Linux `-portable` archives contain the fully static builds; ordinary platform archives use their native system ABI.> **Windows note**: SmartScreen may show a warning for unsigned software. Click **"More info"** → **"Run anyway"**. Verify integrity with `checksums.txt`.@@ -381,7 +382,7 @@ scripts/build.sh --with-ui # with graph visualization# Binary at: build/c/codebase-memory-mcp (codebase-memory-mcp.exe on Windows)```-Every platform builds **one self-contained binary** — no runtime dependencies, no companion executables to keep alongside it.+Every platform builds a **verified runtime set**: the native executable, `cbm-integrations.json`, and—when `--with-ui` is selected—exactly one content-addressed `cbm-ui-<sha256>.pack`. These files are authenticated and published together; do not separate the executable from its sidecars.Run the test suite (6,768 tests across 120 suites):@@ -731,7 +732,7 @@ SQLite databases stored at `~/.cache/codebase-memory-mcp/`. Persists across restTree-sitter alone gives a syntactic AST. That handles naming, structure, and call sites well, but it can't tell you that `user.profile.display_name()` resolves to `Profile.display_name` declared three modules away — tree-sitter doesn't track imports, generics, inheritance, or stdlib types.-codebase-memory-mcp ships a **lightweight C implementation of language type-resolution algorithms, structurally inspired by and compatible with major language servers** (tsserver / typescript-go, pyright, gopls, Roslyn, Eclipse JDT, rust-analyzer), embedded directly into the static binary. No language server process, no per-project setup, no API key. We call this layer **Hybrid LSP**: it runs alongside tree-sitter on every parse and refines invocation resolution (`CALLS` / `RESOLVED_CALLS`) and callable-value resolution (`CALL_REFERENCE`, with ambiguous values retained as `USAGE`) using type information, so the resulting graph mirrors what an IDE "Go to Definition" would resolve.+codebase-memory-mcp ships a **lightweight C implementation of language type-resolution algorithms, structurally inspired by and compatible with major language servers** (tsserver / typescript-go, pyright, gopls, Roslyn, Eclipse JDT, rust-analyzer), embedded directly into the native executable. No language server process, no per-project setup, no API key. We call this layer **Hybrid LSP**: it runs alongside tree-sitter on every parse and refines invocation resolution (`CALLS` / `RESOLVED_CALLS`) and callable-value resolution (`CALL_REFERENCE`, with ambiguous values retained as `USAGE`) using type information, so the resulting graph mirrors what an IDE "Go to Definition" would resolve.**Languages with full Hybrid LSP:**@@ -781,21 +782,21 @@ src/discover/ File discovery (.gitignore, .cbmignore, symlink handling)watcher/ Background auto-sync (git polling, adaptive intervals)traces/ Runtime trace ingestion- ui/ Embedded HTTP server + 3D graph visualization+ ui/ Local HTTP server + verified external 3D-UI asset packfoundation/ Platform abstractions (threads, filesystem, logging, memory)internal/cbm/ Vendored tree-sitter grammars (158 languages) + AST extraction engine```## Security-Every release binary is verified through a multi-layer pipeline before publication:+Every release is verified through a multi-layer pipeline before publication:-- **VirusTotal** — all binaries scanned by 70+ antivirus engines (zero detections required to publish)+- **VirusTotal** — every release object is scanned (minimum 50 decisive engines; zero malicious and zero suspicious required). Release notes summarize the archive rows and link durable public association, exact-scan-set, and per-object result files containing every measured engine count and VirusTotal report URL.- **SLSA Level 3** — cryptographic build provenance generated by the trusted GitHub Actions build workflow; verify with `gh attestation verify <file> --repo DeusData/codebase-memory-mcp --signer-workflow DeusData/codebase-memory-mcp/.github/workflows/_build.yml`- **Sigstore cosign** — keyless signatures on all artifacts; bundles included in every release- **SHA-256 checksums** — `checksums.txt` published with every release; verified by both install scripts before extraction- **CodeQL SAST** — blocks release pipeline if any open alerts remain-- **Zero runtime dependencies** — no transitive supply chain; all libraries vendored at compile time+- **No language-runtime dependency chain** — libraries are vendored at compile time; the small release-owned runtime assets are checksum-verified and content-addressed### v0.7.0 VirusTotal scansdiff --git a/SECURITY.md b/SECURITY.mdindex d00b3c556..37a61dcb6 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -4,7 +4,7 @@codebase-memory-mcp interacts deeply with your filesystem. It reads source files across your entire codebase, writes to agent configuration files, and spawns background processes. This is inherent to what it does — not a bug.-**If you are uncomfortable with these access patterns**, please audit the source code before running. The full source is available in this repository. Release binaries produced by the current release pipeline are verifiably built from this source and can be independently verified via SLSA Build Level 3 provenance, Sigstore signatures, and SHA-256 checksums (see [Verification](#verification) below).+**If you are uncomfortable with these access patterns**, please audit the source code before running. The full source is available in this repository. Release archives produced by the current release pipeline are verifiably built from this source and can be independently verified via SLSA Build Level 3 provenance, Sigstore signatures, and SHA-256 checksums (see [Verification](#verification) below). Each archive contains a native executable and its authenticated release-owned runtime assets.We are humans and can make mistakes. We take security seriously — it is Priority #1 for this project — but we cannot guarantee perfection. By using this software you accept responsibility for evaluating whether it meets your own security requirements.@@ -95,7 +95,7 @@ disclosure. Research conducted under this policy is considered authorised.## Security Measures-This project implements multiple layers of security verification. Every release binary must pass all checks before users can download it (draft → verify → publish flow).+This project implements multiple layers of security verification. Every release archive and its extracted runtime objects must pass all checks before users can download it (draft → verify → publish flow).### Build-Time (CI — every commit)@@ -122,11 +122,11 @@ This project implements multiple layers of security verification. Every releaseReleases are created as **drafts** (invisible to users) and only published after all verification passes:-1. **SLSA Build Level 3 provenance for release binaries** — cryptographic attestation generated inside the trusted GitHub Actions build workflow immediately after each release archive is produced+1. **SLSA Build Level 3 provenance for release archives** — cryptographic attestation generated inside the trusted GitHub Actions build workflow immediately after each release archive is produced2. **Sigstore cosign signing** — keyless digital signatures verifiable by anyone3. **SBOM** — Software Bill of Materials (SPDX) listing all vendored dependencies4. **SHA-256 checksums** — published with every release-5. **VirusTotal scanning** — all binaries scanned by 70+ antivirus engines (zero-tolerance: any detection blocks the release)+5. **VirusTotal scanning** — every distinct shipped archive, member, and UI-asset byte object is scanned. Each completed analysis must contain at least 50 decisive engine results, zero malicious verdicts, and zero suspicious verdicts. Release notes summarize archive results and link durable public association, exact-scan-set, per-object-result, and evidence-checksum assets.6. **OpenSSF Scorecard** — repository security health scoreScope of the SLSA claim: this is a build provenance claim for release@@ -137,7 +137,9 @@ not mean the source code is vulnerability-free or that maintainers cannot changesource. Consumers should verify the signer workflow, not only repositoryownership.-If ANY antivirus engine flags ANY binary, the release stays as a draft and is not published until the issue is investigated and resolved.+If any antivirus engine flags any scanned release object, the release stays as a+draft and is not published until the issue is investigated and resolved. There+is no exception path in this release gate.### Code-Level Defenses@@ -146,14 +148,16 @@ If ANY antivirus engine flags ANY binary, the release stays as a draft and is no- **CORS locked to localhost** — graph UI only accessible from localhost origins- **Path containment** — `realpath()` check prevents reading files outside project root- **Process-kill restriction** — only server-spawned PIDs can be terminated-- **SHA-256 checksum verification** — update command verifies downloaded binary before installing+- **Release-set verification** — installers verify downloaded archives, then the+ candidate executable authenticates its adjacent runtime assets before+ activation### Verification-Users can independently verify any release binary:+Users can independently verify any release archive and the runtime set it contains:```bash-# SLSA Build Level 3 provenance for release binaries+# SLSA Build Level 3 provenance for release archivesgh attestation verify <downloaded-file> \--repo DeusData/codebase-memory-mcp \--signer-workflow DeusData/codebase-memory-mcp/.github/workflows/_build.yml@@ -164,7 +168,7 @@ cosign verify-blob --bundle <file>.bundle <file># SHA-256 checksumsha256sum -c checksums.txt-# VirusTotal (upload binary or check the report links in the release notes)+# VirusTotal (follow the durable per-object results link in the release notes)# https://www.virustotal.com/```diff --git a/THIRD_PARTY.md b/THIRD_PARTY.mdindex e0a1fc82e..f33d0ce83 100644--- a/THIRD_PARTY.md+++ b/THIRD_PARTY.md@@ -66,7 +66,7 @@ License summary:- **Copyright:** (c) 2025 InterSystems Corporation- **Vendored at:** `internal/cbm/vendored/grammars/objectscript_udl/`, `internal/cbm/vendored/grammars/objectscript_routine/`- **Pinned commit:** `a7ffcdf`-- **Notes:** InterSystems-maintained grammar for the ObjectScript language (InterSystems IRIS / Caché). Vendor-maintained; not in nvim-treesitter or Helix registries. Each `scanner.c`'s upstream `#include "../../common/scanner.h"` is repointed to a per-directory `objectscript_common.h` (verbatim copy of upstream `common/scanner.h`).+- **Notes:** InterSystems-maintained grammar for the ObjectScript language (InterSystems IRIS / Caché). Vendor-maintained; not in nvim-treesitter or Helix registries. Each `scanner.c`'s upstream `#include "../../common/scanner.h"` is repointed to a per-directory `objectscript_common.h` copied from upstream `common/scanner.h`; two loop counters in that copy are widened from `uint8_t` to `int` as documented in `internal/cbm/vendored/grammars/MANIFEST.md`.## Vendored C/C++ Libraries@@ -142,13 +142,17 @@ follows:documentation and language specifications; no upstream source code wasextracted or transcribed.-## Embedded Graph UI+## External Graph UI asset pack-Release binaries built with `--with-ui` embed the compiled `graph-ui/`-frontend bundle. Its npm dependencies (React, three.js, @react-three/*,-radix-ui, lucide-react, tailwindcss, and friends) are all under permissive-licenses (MIT / ISC / Apache-2.0 / Zlib); the exact set is recorded in+Release builds made with `--with-ui` ship the compiled `graph-ui/` frontend in+a deterministic, content-addressed `cbm-ui-<sha256>.pack` beside the native+executable. The executable contains only the expected pack name, size, and+SHA-256; it does not contain the HTML, JavaScript, or CSS payload.++The pack's npm dependencies (React, three.js, @react-three/*, radix-ui,+lucide-react, tailwindcss, and friends) are all under permissive licenses+(MIT / ISC / Apache-2.0 / Zlib). The exact set is recorded in`graph-ui/package.json` and `graph-ui/package-lock.json`, and the per-packagelicense texts of the production bundle are appended to the-`THIRD_PARTY_NOTICES.md` shipped inside the `-ui` release archives-(generated by `scripts/gen-ui-licenses.py`).+`THIRD_PARTY_NOTICES.md` shipped inside each `-ui` release archive (generated+by `scripts/gen-ui-licenses.py`).diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex e0a589536..fae2af19e 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -106,7 +106,7 @@ Current format:Notes:-- If the UI-enabled binary has embedded assets and no UI config file exists yet, the UI auto-enables on first run.+- If a UI-enabled binary finds its verified external asset pack and no UI config file exists yet, the UI auto-enables on first run. Missing or invalid assets leave the MCP/daemon service available and keep the UI disabled.- `CBM_CACHE_DIR` changes both the UI config location and the runtime settings database location.- CBM resolves `CBM_CACHE_DIR` to one canonical per-account cache root. A process configured with a different root fails while any CBM session or command is active; close them before switching roots.diff --git a/docs/index.html b/docs/index.htmlindex 28a09a9d7..a8d7d35cc 100644--- a/docs/index.html+++ b/docs/index.html@@ -4,7 +4,7 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>codebase-memory-mcp — Code Intelligence Knowledge Graph for AI Coding Agents</title>- <meta name="description" content="codebase-memory-mcp is an open-source MCP server that indexes any codebase into a persistent knowledge graph so AI coding agents answer structural questions with ~120x fewer tokens. 158 languages, Hybrid LSP type resolution, local semantic vector search, code-clone detection, sub-1ms queries, Linux kernel indexed in 3 minutes. Single static C binary, zero dependencies. One command configures 43 automatic/conditional client surfaces.">+ <meta name="description" content="codebase-memory-mcp is an open-source MCP server that indexes any codebase into a persistent knowledge graph so AI coding agents answer structural questions with ~120x fewer tokens. 158 languages, Hybrid LSP type resolution, local semantic vector search, code-clone detection, sub-1ms queries, Linux kernel indexed in 3 minutes. Native executable with verified assets and no language runtime. One command configures 43 automatic/conditional client surfaces."><meta name="keywords" content="MCP server, code intelligence, knowledge graph, tree-sitter, Hybrid LSP, semantic code search, code embeddings, code clone detection, cross-repo analysis, data-flow analysis, Claude Code, Codex CLI, Gemini CLI, Cursor, Zed, code exploration, token reduction, call graph, dead code detection"><meta name="author" content="DeusData"><meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">@@ -12,7 +12,7 @@<!-- Open Graph --><meta property="og:title" content="codebase-memory-mcp — Code Intelligence Knowledge Graph for AI Coding Agents">- <meta property="og:description" content="Index any codebase into a persistent knowledge graph. AI agents answer structural questions with ~120x fewer tokens. 158 languages, Hybrid LSP, sub-1ms queries, single static C binary.">+ <meta property="og:description" content="Index any codebase into a persistent knowledge graph. AI agents answer structural questions with ~120x fewer tokens. 158 languages, Hybrid LSP, sub-1ms queries, native executable with verified assets."><meta property="og:type" content="website"><meta property="og:url" content="https://deusdata.github.io/codebase-memory-mcp/"><meta property="og:image" content="https://deusdata.github.io/codebase-memory-mcp/graph-ui-screenshot.png">@@ -24,7 +24,7 @@<!-- Twitter Card --><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="codebase-memory-mcp — Code Intelligence for AI Coding Agents">- <meta name="twitter:description" content="Index any codebase into a knowledge graph. ~120x fewer tokens for AI code exploration. 158 languages, Hybrid LSP, sub-1ms queries, single static C binary.">+ <meta name="twitter:description" content="Index any codebase into a knowledge graph. ~120x fewer tokens for AI code exploration. 158 languages, Hybrid LSP, sub-1ms queries, native executable with verified assets."><meta name="twitter:image" content="https://deusdata.github.io/codebase-memory-mcp/graph-ui-screenshot.png"><link rel="canonical" href="https://deusdata.github.io/codebase-memory-mcp/">@@ -41,7 +41,7 @@"applicationSubCategory": "Model Context Protocol (MCP) server","operatingSystem": "macOS, Linux, Windows","softwareVersion": "0.8.1",- "description": "An open-source MCP server that indexes a codebase into a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links, so AI coding agents answer structural questions with roughly 120x fewer tokens than file-by-file search. Parses 158 languages via tree-sitter with Hybrid LSP semantic type resolution for 9 language families. Ships as a single static C binary with zero runtime dependencies.",+ "description": "An open-source MCP server that indexes a codebase into a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links, so AI coding agents answer structural questions with roughly 120x fewer tokens than file-by-file search. Parses 158 languages via tree-sitter with Hybrid LSP semantic type resolution for 9 language families. Ships as a native executable with authenticated release-owned assets; the native install needs no language runtime.","url": "https://deusdata.github.io/codebase-memory-mcp/","downloadUrl": "https://github.com/DeusData/codebase-memory-mcp/releases/latest","codeRepository": "https://github.com/DeusData/codebase-memory-mcp",@@ -125,7 +125,7 @@"name": "What is codebase-memory-mcp?","acceptedAnswer": {"@type": "Answer",- "text": "codebase-memory-mcp is an open-source Model Context Protocol (MCP) server that indexes a codebase into a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. AI coding agents query that graph instead of reading files one by one, answering structural questions with roughly 120x fewer tokens. It parses 158 languages and ships as a single static C binary with no runtime dependencies."+ "text": "codebase-memory-mcp is an open-source Model Context Protocol (MCP) server that indexes a codebase into a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. AI coding agents query that graph instead of reading files one by one, answering structural questions with roughly 120x fewer tokens. It parses 158 languages and ships as a native executable with authenticated release-owned assets; the native install needs no language runtime."}},{@@ -165,7 +165,7 @@"name": "Does codebase-memory-mcp send my code anywhere?","acceptedAnswer": {"@type": "Answer",- "text": "No. All indexing and querying happen 100% locally on your machine. There is no embedded LLM and no API key — your MCP client acts as the intelligence layer. Release binaries are signed, checksummed, and scanned by 70+ antivirus engines."+ "text": "No. All indexing and querying happen 100% locally on your machine. There is no embedded LLM and no API key — your MCP client acts as the intelligence layer. Release archives are signed and checksummed, and every distinct shipped archive, member, and UI-asset byte object is submitted to VirusTotal; release notes record its measured 0/N result, with at least 50 decisive engines and zero malicious or suspicious verdicts required."}},{@@ -444,7 +444,7 @@The fastest, most efficient code intelligence engine for AI coding agents. It indexes anyrepository into a persistent knowledge graph — full-indexing an average repo in seconds and theLinux kernel in 3 minutes — so your agent answers structural questions with ~120x fewer tokens.- Tree-sitter parsing across 158 languages, Hybrid LSP type resolution, single static C binary.+ Tree-sitter parsing across 158 languages, Hybrid LSP type resolution, native executable with verified assets.</p><div><div class="stat"><div class="number">~120x</div><div class="label">fewer tokens</div></div>@@ -483,7 +483,8 @@Protocol (MCP)</a> server that indexes a codebase into a persistent knowledge graph of functions,classes, call chains, HTTP routes, and cross-service links. Instead of reading files one at a time,an AI coding agent queries the graph — answering structural questions with roughly 120x fewer- tokens. It parses 158 languages and ships as a single static C binary with zero runtime dependencies.+ tokens. It parses 158 languages and ships as a native executable with authenticated release-owned assets;+ the native install needs no language runtime.</p><p class="muted">It is a structural-analysis backend, not a chatbot: there is no embedded LLM and no API key. Your@@ -515,8 +516,8 @@<section id="install"><h2>How do I install codebase-memory-mcp?</h2><p class="lead">- Install with a single command, then tell your agent to index the project. It is a single static C binary for- macOS, Linux, and Windows — no Docker, no runtime dependencies, no API key.+ Install with a single command, then tell your agent to index the project. The native runtime set contains+ an executable with verified assets for macOS, Linux, and Windows — no Docker, language runtime, or API key.</p><div class="install-block"><span class="comment"># 1. One-line install (macOS / Linux). Add --ui for the 3D graph UI.</span><br>@@ -584,7 +585,7 @@codebase-memory-mcp ships a <strong>lightweight C implementation of language type-resolutionalgorithms, structurally inspired by and compatible with major language servers</strong> —tsserver/typescript-go, pyright, gopls, Roslyn, Eclipse JDT, and rust-analyzer —- embedded directly into the single static C binary. There is no language-server process, no+ embedded directly into the native executable. There is no language-server process, noper-project setup, and no API key. This layer runs alongside tree-sitter on every parse and refines<code>CALLS</code>, <code>USAGE</code>, and <code>RESOLVED_CALLS</code> edges with type information,so the graph mirrors what an IDE "Go to Definition" would resolve.@@ -706,8 +707,8 @@<p>Language-server-grade type inference for Python, TS/JS, PHP, C#, Go, C/C++, Java, Kotlin, and Rust — embedded in the binary, no server process or per-project setup.</p></div><div class="feature">- <h3>Pure C, zero dependencies</h3>- <p>A single static C binary for macOS, Linux, and Windows. No Docker, no runtime, no API keys. Download, run <code>install</code>, done.</p>+ <h3>Pure C, no language runtime</h3>+ <p>A native executable with authenticated release-owned assets for macOS, Linux, and Windows. The native install needs no Docker, language runtime, or API keys; fully static Linux builds are available in the <code>-portable</code> archives.</p></div><div class="feature"><h3>Call-graph tracing</h3>@@ -735,7 +736,7 @@</div><div class="feature"><h3>3D graph visualization</h3>- <p>An optional UI binary serves an interactive 3D graph at <code>localhost:9749</code> to explore nodes, edges, and clusters visually.</p>+ <p>The optional UI variant adds one verified, content-addressed frontend pack and serves an interactive 3D graph at <code>localhost:9749</code> to explore nodes, edges, and clusters visually.</p></div><div class="feature"><h3>15 MCP tools</h3>@@ -790,7 +791,9 @@<h3>Does codebase-memory-mcp send my code anywhere?</h3><p>No. All indexing and querying happen 100% locally. There is no embedded LLM and no API key. Release- binaries are signed, checksummed, and scanned by 70+ antivirus engines.</p>+ archives are signed and checksummed, and every distinct shipped archive, member, and UI-asset byte object+ is submitted to VirusTotal. Release notes+ record its measured 0/N result; at least 50 decisive engines and zero malicious or suspicious verdicts are required.</p><h3>Does it support semantic or natural-language code search?</h3><p>Yes. Alongside structural and full-text search, <code>search_graph</code>'s <code>semantic_query</code>@@ -800,8 +803,9 @@edges between similar functions and <code>SIMILAR_TO</code> edges for near-clone detection.</p><h3>Do I need Docker or a runtime?</h3>- <p>No. It is a single static C binary with zero runtime dependencies for macOS (arm64/amd64), Linux- (arm64/amd64), and Windows (amd64).</p>+ <p>The native install needs no language runtime. It is a native executable with authenticated release-owned+ assets for macOS (arm64/amd64), Linux (arm64/amd64), and Windows (amd64); npm, PyPI, and Go wrapper+ installations naturally use their package runtime.</p><h3>How does it stay up to date as I edit code?</h3><p>A background watcher detects file changes and re-indexes incrementally — typically a sub-milliseconddiff --git a/docs/llms.txt b/docs/llms.txtindex 32eb41640..f7edd0316 100644--- a/docs/llms.txt+++ b/docs/llms.txt@@ -1,6 +1,6 @@# codebase-memory-mcp-> An open-source Model Context Protocol (MCP) server that indexes a codebase into a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. AI coding agents query the graph instead of reading files one by one, answering structural questions with roughly 120x fewer tokens (~3,400 vs ~412,000 across five structural queries). Parses 158 languages via vendored tree-sitter grammars, with Hybrid LSP semantic type resolution for Python, TypeScript/JavaScript, PHP, C#, Go, C/C++, Java, Kotlin, and Rust. It also generates semantic graph edges (SEMANTICALLY_RELATED for vocabulary-mismatch matches, SIMILAR_TO for near-clone detection) and supports semantic vector search via bundled nomic-embed-code embeddings compiled into the binary — no API key, no Ollama, no Docker. Ships as a single static C binary (zero runtime dependencies) for macOS, Linux, and Windows. All processing is local — the embeddings run on-device; there is no embedded LLM and no API key.+> An open-source Model Context Protocol (MCP) server that indexes a codebase into a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. AI coding agents query the graph instead of reading files one by one, answering structural questions with roughly 120x fewer tokens (~3,400 vs ~412,000 across five structural queries). Parses 158 languages via vendored tree-sitter grammars, with Hybrid LSP semantic type resolution for Python, TypeScript/JavaScript, PHP, C#, Go, C/C++, Java, Kotlin, and Rust. It also generates semantic graph edges (SEMANTICALLY_RELATED for vocabulary-mismatch matches, SIMILAR_TO for near-clone detection) and supports semantic vector search via bundled nomic-embed-code embeddings compiled into the native executable — no API key, no Ollama, no Docker. Ships a native executable with an authenticated integration asset; the UI variant adds one content-addressed frontend pack. All processing is local — the embeddings run on-device; there is no embedded LLM and no API key.## Key facts@@ -15,7 +15,7 @@- Supported agents: 43 automatic/conditional client surfaces (37 automatically detected + 6 conditional/explicit): Claude Code, Codex CLI, Gemini CLI, Zed, OpenCode, Antigravity, Aider, KiloCode, VS Code, Cursor, Windsurf, Augment / Auggie, OpenClaw, Kiro, Junie, Hermes, OpenHands, Cline, Warp, Qwen Code, GitHub Copilot CLI, Factory Droid, Crush, Goose, Mistral Vibe, Qoder CLI, Kimi Code CLI, GitLab Duo CLI, Rovo Dev CLI, Amp, Devin CLI / Local, Tabnine, Continue / cn, Visual Studio, TRAE, Roo Code, Amazon Q Developer IDE, CodeBuddy Code CLI, IBM Bob IDE, IBM Bob Shell, Pochi, Pi, and Sourcegraph Cody.- Agent profiles: documented custom-agent formats receive Scout (fast/provisional), Verify (default/task-directed), and Auditor (bounded/full verification) definitions. Every direct tier checks exact path/scope coverage with check_index_coverage and falls back to source for flagged gaps; unsafe child-MCP formats use explicit parent handoff. Kiro and Junie use positive-allowlist Scout/Analysis server profiles (7/11 tools); Qoder combines named-server selection with exact tier-specific MCP tool IDs, while Factory uses exact registered IDs without additive whole-server exposure. Foreign Junie aliases are preserved and force parent handoff.- Performance: Linux kernel (28M LOC, 75K files) full index in 3 minutes → 4.81M nodes, 7.72M edges; Cypher queries in under 1ms.-- Distribution: single static C binary; also npm, PyPI, Homebrew, Scoop, Winget, Chocolatey, AUR, and `go install`.+- Distribution: verified runtime set (native executable plus authenticated release-owned assets); fully static Linux builds are available in the `-portable` archives. Also available through npm, PyPI, Homebrew, Scoop, Winget, Chocolatey, AUR, and `go install`.## Linksdiff --git a/install.ps1 b/install.ps1index a65a1a342..a434e78fb 100644--- a/install.ps1+++ b/install.ps1@@ -21,6 +21,7 @@ $WindowsArchiveNames = @("install.ps1","THIRD_PARTY_NOTICES.md")+$UiPackPattern = '^cbm-ui-[0-9a-f]{64}\.pack$'$BaseUrl = if ($env:CBM_DOWNLOAD_URL) { $env:CBM_DOWNLOAD_URL } else { "https://github.com/$Repo/releases/latest/download" }try { $BaseUri = [Uri]$BaseUrl } catch { $BaseUri = $null }@@ -88,6 +89,50 @@ function Invoke-CbmDownload {}}+function New-CbmExclusiveSiblingTemp {+ param([Parameter(Mandatory=$true)][string]$Destination)++ $directory = [System.IO.Path]::GetDirectoryName($Destination)+ $leaf = [System.IO.Path]::GetFileName($Destination)+ for ($attempt = 0; $attempt -lt 32; $attempt++) {+ $random = [System.IO.Path]::GetRandomFileName()+ $candidate = Join-Path $directory ".$leaf.tmp-$random"+ try {+ $reservation = [System.IO.File]::Open(+ $candidate,+ [System.IO.FileMode]::CreateNew,+ [System.IO.FileAccess]::Write,+ [System.IO.FileShare]::None)+ $reservation.Dispose()+ return $candidate+ } catch [System.IO.IOException] {+ # A collision belongs to someone else. Never remove it; choose a+ # fresh unpredictable sibling and reserve that path exclusively.+ }+ }+ throw "could not reserve an exclusive temporary sibling for $Destination"+}++function New-CbmExclusiveTempDirectory {+ param([Parameter(Mandatory=$true)][string]$ParentDirectory)++ for ($attempt = 0; $attempt -lt 32; $attempt++) {+ $candidate = Join-Path $ParentDirectory (+ "cbm-install-" + [guid]::NewGuid().ToString("N")+ )+ try {+ # Without -Force, an existing path is never adopted. Only return a+ # directory successfully created by this installer invocation.+ New-Item -ItemType Directory -Path $candidate -ErrorAction Stop | Out-Null+ return $candidate+ } catch [System.IO.IOException] {+ # A collision belongs to someone else. Never remove it; choose a+ # fresh unpredictable name and try again within the fixed bound.+ }+ }+ throw "could not reserve an exclusive installer temporary directory"+}+# Detect variant from args (--ui or --standard)$Variant = "standard"$SkipConfig = $false@@ -135,8 +180,7 @@ if ($Variant -eq "ui") {$Url = "$BaseUrl/$Archive"# Download-$TmpDir = Join-Path ([System.IO.Path]::GetTempPath()) "cbm-install-$(Get-Random)"-New-Item -ItemType Directory -Path $TmpDir -Force | Out-Null+$TmpDir = New-CbmExclusiveTempDirectory -ParentDirectory ([System.IO.Path]::GetTempPath())Write-Host "Downloading $Archive..."try {@@ -189,7 +233,7 @@ try {# Validate the zip namespace before extraction. Windows paths are# case-insensitive, so two entries that differ only in case are ambiguous and# must never be allowed to overwrite each other. The official five entries are-# required at the archive root with their exact release names.+# required at the archive root; UI adds exactly one hash-shaped pack.try {Add-Type -AssemblyName System.IO.Compression.FileSystem$zip = [System.IO.Compression.ZipFile]::OpenRead("$TmpDir\$Archive")@@ -197,6 +241,8 @@ try {$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)$archiveCounts = @{}foreach ($archiveName in $WindowsArchiveNames) { $archiveCounts[$archiveName] = 0 }+ $uiPackName = $null+ $uiPackCount = 0foreach ($entry in $zip.Entries) {$entryName = $entry.FullName.Replace('\', '/')$isDirectory = $entryName.EndsWith('/')@@ -214,18 +260,28 @@ try {if (-not $seen.Add($pathForSegments)) {throw "duplicate or case-conflicting zip entry: $($entry.FullName)"}- if (-not ($WindowsArchiveNames -ccontains $entryName) -or $isDirectory) {+ if ($isDirectory) {+ throw "archive contains an unexpected root entry: $($entry.FullName)"+ }+ if ($WindowsArchiveNames -ccontains $entryName) {+ $archiveCounts[$entryName] = $archiveCounts[$entryName] + 1+ } elseif ($Variant -eq "ui" -and $entryName -cmatch $UiPackPattern) {+ $uiPackName = $entryName+ $uiPackCount+++ } else {throw "archive contains an unexpected root entry: $($entry.FullName)"}- $archiveCounts[$entryName] = $archiveCounts[$entryName] + 1}foreach ($archiveName in $WindowsArchiveNames) {if ($archiveCounts[$archiveName] -ne 1) {throw "archive must contain exactly one $archiveName"}}- if ($seen.Count -ne $WindowsArchiveNames.Count) {- throw "archive does not match the exact Windows release allowlist"+ $expectedUiPackCount = if ($Variant -eq "ui") { 1 } else { 0 }+ $expectedArchiveCount = $WindowsArchiveNames.Count + $expectedUiPackCount+ if ($uiPackCount -ne $expectedUiPackCount -or+ $seen.Count -ne $expectedArchiveCount) {+ throw "archive does not match the exact $Variant Windows release allowlist"}} finally {$zip.Dispose()@@ -242,6 +298,21 @@ try {Write-Host "Extracting..."Expand-Archive -Path "$TmpDir\$Archive" -DestinationPath $TmpDir -Force+foreach ($archiveName in $WindowsArchiveNames) {+ $extractedMember = Join-Path $TmpDir $archiveName+ if (-not (Test-Path -LiteralPath $extractedMember -PathType Leaf)) {+ Write-Host "error: release member is not a regular file: $archiveName" -ForegroundColor Red+ Remove-Item -Recurse -Force $TmpDir+ exit 1+ }+ $extractedItem = Get-Item -LiteralPath $extractedMember+ if ($extractedItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {+ Write-Host "error: refusing reparse-point release member: $archiveName" -ForegroundColor Red+ Remove-Item -Recurse -Force $TmpDir+ exit 1+ }+}+$DownloadedBinary = Join-Path $TmpDir $BinNameif (-not (Test-Path -LiteralPath $DownloadedBinary -PathType Leaf)) {Write-Host "error: $BinName not found after extraction" -ForegroundColor Red@@ -255,6 +326,29 @@ if ($binaryItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {exit 1}+$DownloadedUiPack = $null+if ($Variant -eq "ui") {+ $DownloadedUiPack = Join-Path $TmpDir $uiPackName+ if (-not (Test-Path -LiteralPath $DownloadedUiPack -PathType Leaf)) {+ Write-Host "error: UI asset pack not found after extraction" -ForegroundColor Red+ Remove-Item -Recurse -Force $TmpDir+ exit 1+ }+ $packItem = Get-Item -LiteralPath $DownloadedUiPack+ if ($packItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {+ Write-Host "error: refusing reparse-point UI asset pack" -ForegroundColor Red+ Remove-Item -Recurse -Force $TmpDir+ exit 1+ }+ $expectedPackDigest = $uiPackName.Substring(7, 64)+ $actualPackDigest = (Get-FileHash -LiteralPath $DownloadedUiPack -Algorithm SHA256).Hash.ToLower()+ if ($expectedPackDigest -cne $actualPackDigest) {+ Write-Host "error: UI asset pack digest does not match its filename" -ForegroundColor Red+ Remove-Item -Recurse -Force $TmpDir+ exit 1+ }+}+# Prove the downloaded binary runs before touching an existing installation.try {$candidateVersion = & $DownloadedBinary --version 2>&1@@ -266,32 +360,12 @@ try {exit 1}+# The candidate publishes the runtime set under one native activation guard,+# with sidecars before the executable and retained per-file backups for+# cooperative rollback. This is recoverable/fail-closed ordering, not a claim+# that several filesystem entries change in one crash-atomic transaction.$Dest = Join-Path $InstallDir $BinName-# Retire the running installation before replacing it. Windows keeps an image-# lock on a running .exe: the file cannot be overwritten, but it CAN be renamed-# out of the way, which is what makes an in-place update possible from here.-if (Test-Path -LiteralPath $Dest -PathType Leaf) {- try { & $Dest daemon stop 2>&1 | Out-Null } catch { }- $retired = "$Dest.retired-$(Get-Date -Format yyyyMMddHHmmss)"- $renamed = $false- foreach ($attempt in 1..10) {- try { Move-Item -LiteralPath $Dest -Destination $retired -Force -ErrorAction Stop; $renamed = $true; break }- catch { Start-Sleep -Milliseconds 500 }- }- if (-not $renamed) {- Write-Host "error: could not retire the existing $BinName - close all running" -ForegroundColor Red- Write-Host " codebase-memory-mcp sessions and coding agents, then re-run." -ForegroundColor Red- Remove-Item -Recurse -Force $TmpDir -ErrorAction SilentlyContinue- exit 1- }- # A retired image stays locked until its last process exits; delete it when- # we can, and leave it for the next run when we cannot. Never fail here.- Remove-Item -LiteralPath $retired -Force -ErrorAction SilentlyContinue-}-Get-ChildItem -LiteralPath $InstallDir -Filter "$BinName.retired-*" -ErrorAction SilentlyContinue |- ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force -ErrorAction SilentlyContinue }-$InstallArgs = @("install", "-y", "--force", "--dir=$InstallDir")if ($SkipConfig) { $InstallArgs += "--skip-config" }& $DownloadedBinary @InstallArgs@@ -312,35 +386,21 @@ if ($LASTEXITCODE -ne 0) {$DownloadedInstaller = Join-Path $TmpDir "install.ps1"if (Test-Path -LiteralPath $DownloadedInstaller -PathType Leaf) {$InstallerDest = Join-Path $InstallDir "install.ps1"- $InstallerTmp = "$InstallerDest.new"+ $InstallerTmp = $nulltry {+ $InstallerTmp = New-CbmExclusiveSiblingTemp -Destination $InstallerDestCopy-Item -LiteralPath $DownloadedInstaller -Destination $InstallerTmp -Force -ErrorAction StopMove-Item -LiteralPath $InstallerTmp -Destination $InstallerDest -Force -ErrorAction Stop+ $InstallerTmp = $nullWrite-Host "Installed updater -> $InstallerDest"} catch {- Remove-Item -LiteralPath $InstallerTmp -Force -ErrorAction SilentlyContinue+ if ($InstallerTmp) {+ Remove-Item -LiteralPath $InstallerTmp -Force -ErrorAction SilentlyContinue+ }Write-Host "note: could not place install.ps1 in $InstallDir (update will explain where to find it)"}}-# Place the integration-template asset beside the installed binary, mirroring-# install.sh. `install` above published a verified copy to ~/.cbm/assets, but a-# later install/uninstall run from $InstallDir resolves the asset next to the-# binary first; without this copy that lookup misses and the run fails closed-# with "integration assets missing".-$DownloadedAsset = Join-Path $TmpDir "cbm-integrations.json"-if (Test-Path -LiteralPath $DownloadedAsset -PathType Leaf) {- $AssetDest = Join-Path $InstallDir "cbm-integrations.json"- $AssetTmp = "$AssetDest.new"- try {- Copy-Item -LiteralPath $DownloadedAsset -Destination $AssetTmp -Force -ErrorAction Stop- Move-Item -LiteralPath $AssetTmp -Destination $AssetDest -Force -ErrorAction Stop- } catch {- Remove-Item -LiteralPath $AssetTmp -Force -ErrorAction SilentlyContinue- Write-Host "note: could not place cbm-integrations.json in $InstallDir (asset resolves from ~/.cbm/assets)"- }-}-# Verifytry {$ver = & $Dest --version 2>&1diff --git a/install.sh b/install.shindex e0551055e..b9e9cea3f 100755--- a/install.sh+++ b/install.sh@@ -231,6 +231,71 @@ if [ "$EXPECTED" != "$ACTUAL" ]; thenfiecho "Checksum verified."+# Validate the complete archive namespace before extraction. Standard releases+# are the canonical five files; UI releases add exactly one root-level,+# content-addressed pack. Anything else is a release-integrity failure, not a+# sidecar to ignore.+if [ "$OS" = "windows" ]; then+ ARCHIVE_BINARY="codebase-memory-mcp.exe"+ ARCHIVE_INSTALLER="install.ps1"+else+ ARCHIVE_BINARY="codebase-memory-mcp"+ ARCHIVE_INSTALLER="install.sh"+fi+ARCHIVE_MEMBERS_FILE="$DLDIR/archive-members.txt"+if [ "$EXT" = "zip" ]; then+ if ! unzip -Z1 "$DLDIR/$ARCHIVE" > "$ARCHIVE_MEMBERS_FILE"; then+ echo "error: could not enumerate release archive" >&2+ exit 1+ fi+else+ if ! tar -tzf "$DLDIR/$ARCHIVE" > "$ARCHIVE_MEMBERS_FILE"; then+ echo "error: could not enumerate release archive" >&2+ exit 1+ fi+fi++BINARY_MEMBERS=0+INTEGRATION_MEMBERS=0+LICENSE_MEMBERS=0+INSTALLER_MEMBERS=0+NOTICE_MEMBERS=0+UI_PACK_MEMBERS=0+ARCHIVE_MEMBER_COUNT=0+UI_PACK_NAME=""+while IFS= read -r member || [ -n "$member" ]; do+ ARCHIVE_MEMBER_COUNT=$((ARCHIVE_MEMBER_COUNT + 1))+ case "$member" in+ "$ARCHIVE_BINARY") BINARY_MEMBERS=$((BINARY_MEMBERS + 1)) ;;+ cbm-integrations.json) INTEGRATION_MEMBERS=$((INTEGRATION_MEMBERS + 1)) ;;+ LICENSE) LICENSE_MEMBERS=$((LICENSE_MEMBERS + 1)) ;;+ "$ARCHIVE_INSTALLER") INSTALLER_MEMBERS=$((INSTALLER_MEMBERS + 1)) ;;+ THIRD_PARTY_NOTICES.md) NOTICE_MEMBERS=$((NOTICE_MEMBERS + 1)) ;;+ *)+ if [ "$VARIANT" = "ui" ] &&+ [[ "$member" =~ ^cbm-ui-[0-9a-f]{64}\.pack$ ]]; then+ UI_PACK_MEMBERS=$((UI_PACK_MEMBERS + 1))+ UI_PACK_NAME="$member"+ else+ echo "error: release archive contains unexpected member: $member" >&2+ exit 1+ fi+ ;;+ esac+done < "$ARCHIVE_MEMBERS_FILE"++EXPECTED_MEMBER_COUNT=5+if [ "$VARIANT" = "ui" ]; then+ EXPECTED_MEMBER_COUNT=6+fi+if [ "$BINARY_MEMBERS" -ne 1 ] || [ "$INTEGRATION_MEMBERS" -ne 1 ] ||+ [ "$LICENSE_MEMBERS" -ne 1 ] || [ "$INSTALLER_MEMBERS" -ne 1 ] ||+ [ "$NOTICE_MEMBERS" -ne 1 ] || [ "$UI_PACK_MEMBERS" -ne $((EXPECTED_MEMBER_COUNT - 5)) ] ||+ [ "$ARCHIVE_MEMBER_COUNT" -ne "$EXPECTED_MEMBER_COUNT" ]; then+ echo "error: release archive does not match the exact $VARIANT member set" >&2+ exit 1+fi+# Extractecho "Extracting..."if [ "$EXT" = "zip" ]; then@@ -239,12 +304,41 @@ elsetar -xzf "$DLDIR/$ARCHIVE" -C "$DLDIR"fi-DLBIN="$DLDIR/codebase-memory-mcp"-if [ ! -f "$DLBIN" ]; then+for extracted_member in "$ARCHIVE_BINARY" cbm-integrations.json LICENSE \+ "$ARCHIVE_INSTALLER" THIRD_PARTY_NOTICES.md; do+ if [ ! -f "$DLDIR/$extracted_member" ] || [ -L "$DLDIR/$extracted_member" ]; then+ echo "error: release member is not a regular file: $extracted_member" >&2+ exit 1+ fi+done++DLBIN="$DLDIR/$ARCHIVE_BINARY"+if [ ! -f "$DLBIN" ] || [ -L "$DLBIN" ]; thenecho "error: binary not found after extraction" >&2exit 1fi+DL_UI_PACK=""+if [ "$VARIANT" = "ui" ]; then+ DL_UI_PACK="$DLDIR/$UI_PACK_NAME"+ if [ ! -f "$DL_UI_PACK" ] || [ -L "$DL_UI_PACK" ]; then+ echo "error: UI asset pack not found after extraction" >&2+ exit 1+ fi+ PACK_EXPECTED="${UI_PACK_NAME#cbm-ui-}"+ PACK_EXPECTED="${PACK_EXPECTED%.pack}"+ if command -v sha256sum &>/dev/null; then+ PACK_ACTUAL=$(sha256sum "$DL_UI_PACK" | awk '{print $1}')+ else+ PACK_ACTUAL=$(shasum -a 256 "$DL_UI_PACK" | awk '{print $1}')+ fi+ PACK_ACTUAL=$(printf '%s' "$PACK_ACTUAL" | tr 'A-F' 'a-f')+ if [ "$PACK_EXPECTED" != "$PACK_ACTUAL" ]; then+ echo "error: UI asset pack digest does not match its filename" >&2+ exit 1+ fi+fi+# macOS: fix signingif [ "$OS" = "darwin" ]; thenecho "Fixing macOS code signing..."@@ -261,7 +355,20 @@ if ! CANDIDATE_VERSION=$("$DLBIN" --version 2>&1); thenfiecho "Verified candidate: $CANDIDATE_VERSION"+# The candidate publishes the runtime set under one native activation guard,+# with sidecars before the executable and retained per-file backups for+# cooperative rollback. The set is intentionally recoverable/fail-closed, not+# claimed to be a crash-atomic multi-file filesystem transaction.+new_exclusive_sibling_temp() {+ local destination="$1"+ local directory basename+ directory="$(dirname "$destination")"+ basename="$(basename "$destination")"+ mktemp "$directory/.${basename}.tmp.XXXXXX"+}+DEST="$INSTALL_DIR/codebase-memory-mcp"+[ "$OS" = "windows" ] && DEST="$INSTALL_DIR/codebase-memory-mcp.exe"INSTALL_ARGS=(-y --force "--dir=$INSTALL_DIR")if [ "$SKIP_CONFIG" = true ]; thenINSTALL_ARGS+=(--skip-config)@@ -283,36 +390,20 @@ fi# working install, and `update` falls back to explaining where to find it.DL_INSTALLER="$DLDIR/install.sh"if [ -f "$DL_INSTALLER" ]; then- INSTALLER_TMP="$INSTALL_DIR/.install.sh.$$"- if cp "$DL_INSTALLER" "$INSTALLER_TMP" 2>/dev/null &&+ INSTALLER_TMP=""+ if INSTALLER_TMP="$(new_exclusive_sibling_temp "$INSTALL_DIR/install.sh" 2>/dev/null)" &&+ cp "$DL_INSTALLER" "$INSTALLER_TMP" 2>/dev/null &&chmod 755 "$INSTALLER_TMP" 2>/dev/null &&mv -f "$INSTALLER_TMP" "$INSTALL_DIR/install.sh" 2>/dev/null; thenecho "Installed updater -> $INSTALL_DIR/install.sh"else- rm -f "$INSTALLER_TMP" 2>/dev/null || true+ # A non-empty path was exclusively created by mktemp above. If+ # reservation failed, leave every pre-existing sibling untouched.+ [ -z "$INSTALLER_TMP" ] || rm -f "$INSTALLER_TMP" 2>/dev/null || trueecho "note: could not place install.sh in $INSTALL_DIR (update will explain where to find it)"fifi-# Place the integration-template asset beside the installed binary. `install`-# above already published a verified copy to ~/.cbm/assets/<version>/, but a-# later `install`/`uninstall` run from INSTALL_DIR resolves the asset next to-# the binary FIRST — and without this copy that lookup misses, so a re-run or an-# uninstall would fail closed with "integration assets missing" even though a-# valid install just completed. Atomic rename, best effort, same rationale as-# the installer copy above.-DL_ASSET="$DLDIR/cbm-integrations.json"-if [ -f "$DL_ASSET" ]; then- ASSET_TMP="$INSTALL_DIR/.cbm-integrations.json.$$"- if cp "$DL_ASSET" "$ASSET_TMP" 2>/dev/null &&- mv -f "$ASSET_TMP" "$INSTALL_DIR/cbm-integrations.json" 2>/dev/null; then- :- else- rm -f "$ASSET_TMP" 2>/dev/null || true- echo "note: could not place cbm-integrations.json in $INSTALL_DIR (asset resolves from ~/.cbm/assets)"- fi-fi-# VerifyVERSION=$("$DEST" --version 2>&1) || {echo "error: installed binary failed to run" >&2diff --git a/internal/cbm/cbm.c b/internal/cbm/cbm.cindex 5d6309c7e..ea149dd9c 100644--- a/internal/cbm/cbm.c+++ b/internal/cbm/cbm.c@@ -707,6 +707,10 @@ const char *cbm_index_quarantine_phase(const char *rel_path) {return (const char *)cbm_ht_get(g_quarantine_set, rel_path);}+#ifdef CBM_ENABLE_TEST_SEAMS+/* Deterministic supervisor fault injection belongs only in explicitly+ * seam-enabled test artifacts. Ordinary release binaries must never expose a+ * filename-selected abort or infinite loop through environment variables. */static void cbm_test_fault_inject(const char *rel_path) {if (!rel_path || !rel_path[0]) {return;@@ -722,6 +726,7 @@ static void cbm_test_fault_inject(const char *rel_path) {}}}+#endif/* Pre-parse nesting guard for pathologically nested input. tree-sitter's GLR* parser recurses once per nesting level inside stack_node_add_link@@ -1148,7 +1153,9 @@ CBMFileResult *cbm_extract_file_ex(const char *source, int source_len, CBMLangua}cbm_index_mark_start(rel_path);+#ifdef CBM_ENABLE_TEST_SEAMScbm_test_fault_inject(rel_path);+#endif// Get language specconst CBMLangSpec *spec = cbm_lang_spec(language);diff --git a/pkg/aur/.SRCINFO b/pkg/aur/.SRCINFOindex 14bf16fe5..79ae675d9 100644--- a/pkg/aur/.SRCINFO+++ b/pkg/aur/.SRCINFO@@ -1,5 +1,5 @@pkgbase = codebase-memory-mcp- pkgdesc = Fast code intelligence engine for AI coding agents — single static binary MCP server+ pkgdesc = Fast code intelligence engine — native executable with verified integration assetpkgver = 0.8.1pkgrel = 1url = https://github.com/DeusData/codebase-memory-mcpdiff --git a/pkg/aur/PKGBUILD b/pkg/aur/PKGBUILDindex 957c682b1..a28f6a7d9 100644--- a/pkg/aur/PKGBUILD+++ b/pkg/aur/PKGBUILD@@ -2,7 +2,7 @@pkgname=codebase-memory-mcppkgver=0.8.1pkgrel=1-pkgdesc="Fast code intelligence engine for AI coding agents — single static binary MCP server"+pkgdesc="Fast code intelligence engine — native executable with verified integration asset"arch=('x86_64' 'aarch64')url="https://github.com/DeusData/codebase-memory-mcp"license=('MIT')@@ -18,6 +18,8 @@ sha256sums_aarch64=('d2f842d1365da5c35d9c5796f57a821c9745267350994346735e1e6e04dpackage() {install -Dm755 "${srcdir}/codebase-memory-mcp" \"${pkgdir}/usr/bin/codebase-memory-mcp"+ install -Dm644 "${srcdir}/cbm-integrations.json" \+ "${pkgdir}/usr/share/codebase-memory-mcp/cbm-integrations.json"install -Dm644 "${srcdir}/LICENSE" \"${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"# Third-party attribution bundle (present in archives since v0.8.1)diff --git a/pkg/chocolatey/codebase-memory-mcp.nuspec b/pkg/chocolatey/codebase-memory-mcp.nuspecindex 5175d96ea..0c8f3f177 100644--- a/pkg/chocolatey/codebase-memory-mcp.nuspec+++ b/pkg/chocolatey/codebase-memory-mcp.nuspec@@ -13,13 +13,14 @@<tags>mcp ai claude code-intelligence codebase developer-tools tree-sitter llm</tags><summary>Fast code intelligence engine for AI coding agents</summary><description>-codebase-memory-mcp is a single static binary MCP server that indexes codebases at-extreme speed and exposes 14 MCP tools for AI coding agents.+codebase-memory-mcp is a native MCP server distributed with authenticated+release-owned runtime assets. Chocolatey retains the complete extracted runtime+set and exposes its executable through a PATH shim.Full indexes an average repository in milliseconds, the Linux kernel (28M LOC) in3 minutes. Answers structural queries in under 1ms. Supports 159 languages via-vendored tree-sitter grammars. Zero dependencies. Plug and play across 11 coding-agents including Claude Code, Codex CLI, Gemini CLI, and Zed.+vendored tree-sitter grammars. No hosted service or API key. Plug and play across+11 coding agents including Claude Code, Codex CLI, Gemini CLI, and Zed.After installation, run:diff --git a/pkg/chocolatey/tools/chocolateyInstall.ps1 b/pkg/chocolatey/tools/chocolateyInstall.ps1index 191ce7f83..3c83ee8c1 100644--- a/pkg/chocolatey/tools/chocolateyInstall.ps1+++ b/pkg/chocolatey/tools/chocolateyInstall.ps1@@ -16,10 +16,3 @@ Install-ChocolateyZipPackage `# Shim the binary so it is on PATH$binPath = Join-Path $installDir 'codebase-memory-mcp.exe'Install-BinFile -Name 'codebase-memory-mcp' -Path $binPath--# Configure coding agents (non-fatal)-try {- & $binPath install -y 2>&1 | Out-Null-} catch {- Write-Warning "Agent configuration failed (non-fatal). Run manually: codebase-memory-mcp install"-}diff --git a/pkg/glama/Dockerfile b/pkg/glama/Dockerfileindex 2b06f7f58..23f0fa702 100644--- a/pkg/glama/Dockerfile+++ b/pkg/glama/Dockerfile@@ -15,12 +15,13 @@ ARG TARGETARCHRUN apt-get update \&& apt-get install -y --no-install-recommends curl ca-certificates \&& curl -fsSL "https://github.com/DeusData/codebase-memory-mcp/releases/latest/download/codebase-memory-mcp-linux-${TARGETARCH}-portable.tar.gz" \- | tar -xz -C /tmp codebase-memory-mcp LICENSE THIRD_PARTY_NOTICES.md \+ | tar -xz -C /tmp codebase-memory-mcp cbm-integrations.json LICENSE THIRD_PARTY_NOTICES.md \&& chmod +x /tmp/codebase-memory-mcp \&& rm -rf /var/lib/apt/lists/*FROM debian:bookworm-slimCOPY --from=fetch /tmp/codebase-memory-mcp /usr/local/bin/codebase-memory-mcp+COPY --from=fetch /tmp/cbm-integrations.json /usr/local/share/codebase-memory-mcp/cbm-integrations.jsonCOPY --from=fetch /tmp/LICENSE /tmp/THIRD_PARTY_NOTICES.md /usr/share/doc/codebase-memory-mcp/ENV CBM_CACHE_DIR=/tmp/cbmENTRYPOINT ["codebase-memory-mcp"]diff --git a/pkg/go/cmd/codebase-memory-mcp/main.go b/pkg/go/cmd/codebase-memory-mcp/main.goindex 5677a7909..ffc8efdfd 100644--- a/pkg/go/cmd/codebase-memory-mcp/main.go+++ b/pkg/go/cmd/codebase-memory-mcp/main.go@@ -17,6 +17,8 @@ import ("crypto/rand""crypto/sha256""encoding/hex"+ "encoding/json"+ "errors""fmt""io""net"@@ -26,16 +28,17 @@ import ("os/exec""path/filepath""runtime"+ "sort""strings""syscall""time")const (- repo = "DeusData/codebase-memory-mcp"- version = "0.8.1"- windowsLauncherName = "codebase-memory-mcp.exe"- windowsPayloadName = "codebase-memory-mcp.payload.exe"+ repo = "DeusData/codebase-memory-mcp"+ version = "0.8.1"+ windowsBinaryName = "codebase-memory-mcp.exe"+ integrationsFileName = "cbm-integrations.json"maxRedirects = 5requestTimeout = 2 * time.Minute@@ -43,30 +46,101 @@ const (responseHeaderTimeout = 30 * time.SecondcandidateTimeout = 15 * time.SecondmaxChecksumManifestSize = 1024 * 1024+ maxReleaseArchiveSize = int64(256 * 1024 * 1024)+ maxArchiveMembers = 64+ maxArchiveMemberSize = int64(256 * 1024 * 1024)+ maxArchiveExpandedSize = int64(512 * 1024 * 1024)- windowsPairLockName = ".codebase-memory-mcp-pair.lock"- windowsPairLockWait = 45 * time.Second- windowsPairOwnerlessStale = 30 * time.Second- windowsPairLockPoll = 25 * time.Millisecond- windowsPairLockOwnerFile = "owner"- windowsPairTransactionTagSize = 16+ runtimeSetLockName = ".codebase-memory-mcp-runtime.lock"+ runtimeSetLockWait = 45 * time.Second+ runtimeSetOwnerlessStale = 30 * time.Second+ runtimeSetLockLease = 5 * time.Minute+ runtimeSetLockHeartbeat = 20 * time.Second+ runtimeSetLegacyStale = time.Hour+ runtimeSetLockPoll = 25 * time.Millisecond+ runtimeSetLockOwnerFile = "owner.json"+ runtimeSetLockTokenSize = 16+ runtimeBackupPrefix = ".cbm-runtime-backup-"+ runtimeBackupRetired = ".retirement-complete"+ runtimeBackupCleanupOnly = ".cleanup-only"+ runtimeBackupBeforeMarkerEvent = "before-retirement-marker"+ runtimeBackupCleanupRemovedEvent = "cleanup-member-removed")-type windowsPairLock struct {+type archiveResourceLimits struct {+ compressedBytes int64+ members int+ memberBytes int64+ expandedBytes int64+}++var defaultArchiveResourceLimits = archiveResourceLimits{+ compressedBytes: maxReleaseArchiveSize,+ members: maxArchiveMembers,+ memberBytes: maxArchiveMemberSize,+ expandedBytes: maxArchiveExpandedSize,+}++type runtimeSetLock struct {path stringtoken string+ file *os.File+}++type runtimeSetLockOwnerRecord struct {+ PID int `json:"pid"`+ Token string `json:"token"`+ LeaseExpires int64 `json:"lease_expires_ms,omitempty"`+}++type runtimeBackupFile struct {+ path string+ digest [sha256.Size]byte}+type runtimeBackupTransaction struct {+ path string+ retired bool+ cleanupOnly bool+ files map[string]runtimeBackupFile+}++// Tests use this observer to distinguish a publisher waiting on the runtime+// lock from one entering the shared publication sequence. Production leaves+// it nil.+var (+ runtimeSetLockWaitObserver func()+ runtimeSetLockClaimObserver func() error+ runtimeBackupCrashObserver func(string, string) error+ runtimeSetProcessAlive = platformRuntimeSetLockProcessAlive+ runtimeMutationSnapshotCleanup = os.RemoveAll+)+func main() {+ mutation := runtimeMutationAction(os.Args[1:])+ if mutation == "update" {+ fmt.Fprintln(+ os.Stderr,+ "This Go wrapper is maintained by Go. Update it with \"go install github.com/DeusData/codebase-memory-mcp/pkg/go/cmd/codebase-memory-mcp@latest\".",+ )+ os.Exit(2)+ }executable, err := ensureBinary()if err != nil {fmt.Fprintf(os.Stderr, "codebase-memory-mcp: %v\n", err)os.Exit(1)}- if err := execBinary(executable, os.Args[1:]); err != nil {+ args := nativeArgs(os.Args[1:])+ if mutation == "install" || mutation == "uninstall" {+ err = execBinaryWithRuntimeLock(executable, args)+ } else {+ err = execBinary(executable, args)+ }+ if err != nil {if runtime.GOOS == "windows" {- if exitErr, ok := err.(*exec.ExitError); ok {- printPortableMutationGuidance(os.Args[1:])+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) {+ printPortableMutationGuidance(args)os.Exit(exitErr.ExitCode())}}@@ -76,78 +150,161 @@ func main() {}func ensureBinary() (string, error) {- payload := binPath()- ready := regularFileExists(payload)- if runtime.GOOS == "windows" {- ready = ready && regularFileExists(windowsLauncherPath())- if ready {- ready = verifyCandidate(windowsLauncherPath()) == nil- }+ binary := binPath()+ ready, err := runtimeSetReadyLocked(+ filepath.Dir(binary), filepath.Base(binary), runtimeVariant(), verifyCandidate,+ )+ if err != nil {+ return "", err}if ready {- return executionPathForOS(payload, runtime.GOOS), nil+ return executionPathForOS(binary, runtime.GOOS), nil}- if err := download(payload); err != nil {+ if err := download(binary); err != nil {return "", err}- return executionPathForOS(payload, runtime.GOOS), nil+ return executionPathForOS(binary, runtime.GOOS), nil}func binPath() string {- name := "codebase-memory-mcp"- if runtime.GOOS == "windows" {- // The payload remains the immutable exact-version pair's readiness- // signal. executionPathForOS selects its adjacent permanent launcher.- name = windowsPayloadName- }- return filepath.Join(cacheDir(), version, name)+ return filepath.Join(+ cacheDir(), version, runtimeVariant(), binaryNameForOS(runtime.GOOS),+ )}-func executionPathForOS(payload, targetOS string) string {+func binaryNameForOS(targetOS string) string {if targetOS == "windows" {- return filepath.Join(filepath.Dir(payload), windowsLauncherName)+ return windowsBinaryName}- return payload+ return "codebase-memory-mcp"}-func windowsLauncherPath() string {- return filepath.Join(filepath.Dir(binPath()), windowsLauncherName)+func executionPathForOS(binary, targetOS string) string {+ return binary}-func regularFileExists(path string) bool {- info, err := os.Stat(path)- return err == nil && info.Mode().IsRegular()+func runtimeVariant() string {+ if strings.EqualFold(os.Getenv("CBM_VARIANT"), "ui") {+ return "ui"+ }+ return "standard"}func printPortableMutationGuidance(args []string) {- action := portableMutationAction(args)- if action == "" {+ action := runtimeMutationAction(args)+ if action != "uninstall" {return}- packageCommand := "go install github.com/DeusData/codebase-memory-mcp/pkg/go/cmd/codebase-memory-mcp@latest"- if action == "uninstall" {- packageCommand = "Remove-Item (Get-Command codebase-memory-mcp).Source"- }+ packageCommand := "Remove-Item (Get-Command codebase-memory-mcp).Source"fmt.Fprintf(os.Stderr,- "This Go Windows copy is portable. Use %q for package maintenance, or run %q once to create a managed launcher with coordinated self-update/uninstall.\n",+ "This Go Windows copy is portable. Use %q for package maintenance, or run %q once to create a managed installation with coordinated self-update/uninstall.\n",packageCommand,"codebase-memory-mcp install --yes",)}-func portableMutationAction(args []string) string {+func runtimeMutationAction(args []string) string {for _, argument := range args {switch argument {- case "cli", "hook-augment", "config", "install", "--help", "-h", "--version":+ case "--help", "-h", "--version":+ return ""+ case "cli", "hook-augment", "config":return ""- case "update", "uninstall":+ case "install", "update", "uninstall":return argument}+ if strings.HasPrefix(argument, "-") {+ continue+ }+ return ""}return ""}+func defaultManagedInstallDir() string {+ if runtime.GOOS == "windows" {+ base := os.Getenv("LOCALAPPDATA")+ if base == "" {+ if home, err := os.UserHomeDir(); err == nil {+ base = filepath.Join(home, "AppData", "Local")+ }+ }+ return filepath.Join(base, "Programs", "codebase-memory-mcp")+ }+ if home, err := os.UserHomeDir(); err == nil {+ return filepath.Join(home, ".local", "bin")+ }+ return filepath.Join(os.TempDir(), "codebase-memory-mcp-managed")+}++func nativeArgs(args []string) []string {+ result := append([]string(nil), args...)+ if runtimeMutationAction(result) != "uninstall" {+ return result+ }+ for _, argument := range result {+ if argument == "--dir" || strings.HasPrefix(argument, "--dir=") {+ return result+ }+ }+ return append(result, "--dir", defaultManagedInstallDir())+}++func mutationTargetDirectory(args []string) (string, bool) {+ for index, argument := range args {+ if strings.HasPrefix(argument, "--dir=") {+ return strings.TrimPrefix(argument, "--dir="), true+ }+ if argument == "--dir" && index+1 < len(args) {+ return args[index+1], true+ }+ }+ return "", false+}++func pathsReferToSameDirectory(left, right string) bool {+ leftAbsolute, leftErr := filepath.Abs(left)+ rightAbsolute, rightErr := filepath.Abs(right)+ if leftErr != nil || rightErr != nil {+ return false+ }+ leftAbsolute = filepath.Clean(leftAbsolute)+ rightAbsolute = filepath.Clean(rightAbsolute)+ if leftAbsolute == rightAbsolute ||+ (runtime.GOOS == "windows" && strings.EqualFold(leftAbsolute, rightAbsolute)) {+ return true+ }+ leftStatus, leftErr := os.Stat(leftAbsolute)+ rightStatus, rightErr := os.Stat(rightAbsolute)+ return leftErr == nil && rightErr == nil &&+ leftStatus.IsDir() && rightStatus.IsDir() &&+ os.SameFile(leftStatus, rightStatus)+}++func mutationSnapshotEnvironment() []string {+ blocked := []string{"CBM_ASSETS_DIR", "CBM_UI_ASSETS_DIR"}+ result := make([]string, 0, len(os.Environ()))+ for _, entry := range os.Environ() {+ separator := strings.IndexByte(entry, '=')+ name := entry+ if separator >= 0 {+ name = entry[:separator]+ }+ drop := false+ for _, blockedName := range blocked {+ if strings.EqualFold(name, blockedName) {+ drop = true+ break+ }+ }+ if !drop {+ result = append(result, entry)+ }+ }+ return result+}+func cacheDir() string {if d := os.Getenv("CBM_CACHE_DIR"); d != "" {return d@@ -195,9 +352,24 @@ func goarch() string {}}+func archiveNamesForOS(platform, binaryName string) []string {+ installer := "install.sh"+ if platform == "windows" {+ installer = "install.ps1"+ }+ return []string{+ binaryName,+ integrationsFileName,+ "LICENSE",+ installer,+ "THIRD_PARTY_NOTICES.md",+ }+}+func download(dest string) error {platform := goos()arch := goarch()+ selectedVariant := runtimeVariant()ext := "tar.gz"if platform == "windows" {ext = "zip"@@ -207,7 +379,14 @@ func download(dest string) error {if platform == "linux" {portable = "-portable"}- archive := fmt.Sprintf("codebase-memory-mcp-%s-%s%s.%s", platform, arch, portable, ext)+ uiPrefix := ""+ if selectedVariant == "ui" {+ uiPrefix = "ui-"+ }+ archive := fmt.Sprintf(+ "codebase-memory-mcp-%s%s-%s%s.%s",+ uiPrefix, platform, arch, portable, ext,+ )url := fmt.Sprintf("https://github.com/%s/releases/download/v%s/%s", repo, version, archive)checksumURL := fmt.Sprintf("https://github.com/%s/releases/download/v%s/checksums.txt", repo, version)@@ -238,43 +417,37 @@ func download(dest string) error {return err}- binName := "codebase-memory-mcp"- requiredNames := []string{binName}- archiveNames := requiredNames- if platform == "windows" {- binName = windowsPayloadName- requiredNames = []string{windowsLauncherName, windowsPayloadName}- archiveNames = []string{- windowsLauncherName,- windowsPayloadName,- "LICENSE",- "install.ps1",- "THIRD_PARTY_NOTICES.md",- }- }+ binName := binaryNameForOS(platform)+ archiveNames := archiveNamesForOS(platform, binName)+ extractNames := []string{binName, integrationsFileName}+ var runtimeNames []stringif ext == "tar.gz" {- if err := extractTarGz(archivePath, tmp, binName); err != nil {+ runtimeNames, err = extractTarGz(+ archivePath, tmp, archiveNames, extractNames, selectedVariant,+ )+ if err != nil {return fmt.Errorf("extraction failed: %w", err)}} else {- if err := extractZip(archivePath, tmp, archiveNames, requiredNames); err != nil {+ runtimeNames, err = extractZip(+ archivePath, tmp, archiveNames, extractNames, selectedVariant,+ )+ if err != nil {return fmt.Errorf("extraction failed: %w", err)}}- for _, name := range requiredNames {+ for _, name := range runtimeNames {extracted := filepath.Join(tmp, name)- if err := os.Chmod(extracted, 0755); err != nil {+ mode := os.FileMode(0644)+ if name == binName {+ mode = 0755+ }+ if err := os.Chmod(extracted, mode); err != nil {return fmt.Errorf("could not set candidate permissions for %s: %w", name, err)}}- if platform == "windows" {- // In portable mode the canonical launcher must successfully resolve the- // adjacent payload before the pair is cached.- if err := verifyCandidate(filepath.Join(tmp, windowsLauncherName)); err != nil {- return fmt.Errorf("downloaded launcher failed verification: %w", err)- }- } else if err := verifyCandidate(filepath.Join(tmp, binName)); err != nil {+ if err := verifyCandidate(filepath.Join(tmp, binName)); err != nil {return err}@@ -282,12 +455,10 @@ func download(dest string) error {return fmt.Errorf("could not create cache dir: %w", err)}- if platform == "windows" {- if err := installWindowsPairAtomically(tmp, filepath.Dir(dest)); err != nil {- return fmt.Errorf("could not install Windows release pair: %w", err)- }- } else if err := installCandidateAtomically(filepath.Join(tmp, binName), dest); err != nil {- return fmt.Errorf("could not install binary: %w", err)+ if err := publishRuntimeSetWithRecovery(+ tmp, filepath.Dir(dest), binName, selectedVariant, verifyCandidate,+ ); err != nil {+ return fmt.Errorf("could not install runtime set: %w", err)}return nil@@ -325,9 +496,16 @@ var httpsOnlyClient = &http.Client{}func httpGet(rawURL, dest string) error {+ return httpGetWithLimit(rawURL, dest, maxReleaseArchiveSize)+}++func httpGetWithLimit(rawURL, dest string, maxBytes int64) error {if err := validateURLScheme(rawURL); err != nil {return err}+ if maxBytes <= 0 {+ return fmt.Errorf("invalid compressed archive safety limit")+ }resp, err := httpsOnlyClient.Get(rawURL) //nolint:gosecif err != nil {return err@@ -336,15 +514,31 @@ func httpGet(rawURL, dest string) error {if resp.StatusCode != http.StatusOK {return fmt.Errorf("HTTP %d for %s", resp.StatusCode, rawURL)}+ if resp.ContentLength > maxBytes {+ return fmt.Errorf(+ "release archive exceeds the %d-byte compressed safety limit",+ maxBytes,+ )+ }f, err := os.Create(dest)if err != nil {return err}- _, copyErr := io.Copy(f, resp.Body)+ written, copyErr := io.Copy(f, io.LimitReader(resp.Body, maxBytes+1))closeErr := f.Close()+ if copyErr == nil && written > maxBytes {+ copyErr = fmt.Errorf(+ "release archive exceeds the %d-byte compressed safety limit",+ maxBytes,+ )+ }if copyErr != nil {+ _ = os.Remove(dest)return copyErr}+ if closeErr != nil {+ _ = os.Remove(dest)+ }return closeErr}@@ -415,422 +609,1413 @@ func verifyChecksum(path, expected string) error {return nil}-func extractTarGz(archivePath, destDir, targetFile string) error {- f, err := os.Open(archivePath)- if err != nil {- return err- }- defer f.Close()- gz, err := gzip.NewReader(f)- if err != nil {- return err- }- defer gz.Close()- tr := tar.NewReader(gz)- found := false- for {- hdr, err := tr.Next()- if err == io.EOF {- break- }- if err != nil {- return err- }- name := strings.ReplaceAll(hdr.Name, "\\", "/")- if name == targetFile {- if found {- os.Remove(filepath.Join(destDir, targetFile))- return fmt.Errorf("duplicate %s in archive", targetFile)- }- found = true- out, err := os.OpenFile(- filepath.Join(destDir, targetFile),- os.O_WRONLY|os.O_CREATE|os.O_EXCL,- 0600,- )- if err != nil {- return err- }- _, copyErr := io.Copy(out, tr) //nolint:gosec- closeErr := out.Close()- if copyErr != nil {- os.Remove(filepath.Join(destDir, targetFile))- return copyErr- }- if closeErr != nil {- os.Remove(filepath.Join(destDir, targetFile))- return closeErr- }- }+func isUIPackName(name string) bool {+ const prefix = "cbm-ui-"+ const suffix = ".pack"+ if len(name) != len(prefix)+sha256.Size*2+len(suffix) ||+ !strings.HasPrefix(name, prefix) || !strings.HasSuffix(name, suffix) {+ return false}- if !found {- return fmt.Errorf("%s not found in archive", targetFile)+ digest := strings.TrimSuffix(strings.TrimPrefix(name, prefix), suffix)+ if digest != strings.ToLower(digest) {+ return false}- return nil+ decoded, err := hex.DecodeString(digest)+ return err == nil && len(decoded) == sha256.Size}-func extractZip(- archivePath, destDir string,- archiveNames, extractNames []string,-) error {- r, err := zip.OpenReader(archivePath)- if err != nil {- return err- }- defer r.Close()- seen := make(map[string]struct{}, len(r.File))+func validateArchiveMemberNames(+ names, archiveNames []string, variant string, caseInsensitive bool,+) (string, error) {required := make(map[string]struct{}, len(archiveNames))- targets := make(map[string]*zip.File, len(extractNames))for _, name := range archiveNames {required[name] = struct{}{}}- for _, f := range r.File {- name, err := validateWindowsZipMember(f.Name)- if err != nil {- return err+ seen := make(map[string]struct{}, len(names))+ found := make(map[string]struct{}, len(archiveNames))+ uiPack := ""+ for _, name := range names {+ key := name+ if caseInsensitive {+ key = strings.ToLower(name)}- key := strings.ToLower(strings.TrimSuffix(name, "/"))- if _, ok := seen[key]; ok {- return fmt.Errorf("duplicate or case-conflicting zip entry: %q", f.Name)+ if _, exists := seen[key]; exists {+ return "", fmt.Errorf(+ "duplicate or case-conflicting archive entry: %q", name,+ )}seen[key] = struct{}{}- if _, ok := required[name]; !ok || f.FileInfo().IsDir() {- return fmt.Errorf(+ _, isRequired := required[name]+ isPack := variant == "ui" && isUIPackName(name)+ if !isRequired && !isPack {+ return "", fmt.Errorf("archive must contain only the exact root files: %s",strings.Join(archiveNames, ", "),)}- for _, extractName := range extractNames {- if name == extractName {- targets[name] = f+ if isPack {+ if uiPack != "" {+ return "", fmt.Errorf(+ "archive must contain exactly one content-addressed UI pack",+ )}+ uiPack = name+ } else {+ found[name] = struct{}{}}}- if len(seen) != len(archiveNames) || len(targets) != len(extractNames) {- return fmt.Errorf(+ expectedCount := len(archiveNames)+ if variant == "ui" {+ expectedCount+++ }+ if len(seen) != expectedCount || len(found) != len(required) ||+ (variant == "ui" && uiPack == "") {+ return "", fmt.Errorf("archive must contain exactly one of each required root file: %s",strings.Join(archiveNames, ", "),)}-- for _, name := range extractNames {- target := targets[name]- rc, err := target.Open()- if err != nil {- return err- }- outputPath := filepath.Join(destDir, name)- out, err := os.OpenFile(- outputPath,- os.O_WRONLY|os.O_CREATE|os.O_EXCL,- 0600,- )- if err != nil {- rc.Close()- return err- }- _, copyErr := io.Copy(out, rc) //nolint:gosec- closeOutErr := out.Close()- closeReadErr := rc.Close()- if copyErr != nil {- os.Remove(outputPath)- return copyErr- }- if closeOutErr != nil {- os.Remove(outputPath)- return closeOutErr- }- if closeReadErr != nil {- os.Remove(outputPath)- return closeReadErr- }- }- return nil+ return uiPack, nil}-func validateWindowsZipMember(raw string) (string, error) {- name := strings.ReplaceAll(raw, "\\", "/")- segmentsName := strings.TrimSuffix(name, "/")- if segmentsName == "" || strings.HasPrefix(name, "/") || strings.Contains(name, ":") {- return "", fmt.Errorf("unsafe zip entry path: %q", raw)- }- for _, segment := range strings.Split(segmentsName, "/") {- if segment == "" || segment == "." || segment == ".." ||- strings.HasSuffix(segment, ".") || strings.HasSuffix(segment, " ") {- return "", fmt.Errorf("unsafe zip entry path: %q", raw)- }+func runtimeArchiveNames(extractNames []string, uiPack string) []string {+ result := append([]string(nil), extractNames...)+ if uiPack != "" {+ result = append(result, uiPack)}- return name, nil+ return result}-func verifyCandidate(path string) error {- ctx, cancel := context.WithTimeout(context.Background(), candidateTimeout)- defer cancel()- cmd := exec.CommandContext(ctx, path, "--version")- cmd.Stdin = nil- cmd.Stdout = io.Discard- cmd.Stderr = io.Discard- if err := cmd.Run(); err != nil {- if ctx.Err() != nil {- return fmt.Errorf("downloaded binary verification timed out: %w", ctx.Err())- }- return fmt.Errorf("downloaded binary failed to run: %w", err)+func validateArchiveResourceLimits(limits archiveResourceLimits) error {+ if limits.compressedBytes <= 0 || limits.members <= 0 ||+ limits.memberBytes <= 0 || limits.expandedBytes <= 0 {+ return fmt.Errorf("invalid archive resource safety limits")}return nil}-func fileSHA256(path string) ([sha256.Size]byte, error) {- var digest [sha256.Size]byte- source, err := os.Open(path)+func requireCompressedArchiveWithinLimit(+ archivePath string, limits archiveResourceLimits,+) error {+ status, err := os.Stat(archivePath)if err != nil {- return digest, err+ return err}- defer source.Close()- hash := sha256.New()- if _, err := io.Copy(hash, source); err != nil {- return digest, err+ if !status.Mode().IsRegular() {+ return fmt.Errorf("release archive is not a regular file")}- copy(digest[:], hash.Sum(nil))- return digest, nil+ if status.Size() > limits.compressedBytes {+ return fmt.Errorf(+ "release archive exceeds the %d-byte compressed safety limit",+ limits.compressedBytes,+ )+ }+ return nil}-func filesEqualSHA256(left, right string) (bool, error) {- leftInfo, err := os.Stat(left)- if err != nil {- return false, err- }- rightInfo, err := os.Stat(right)- if err != nil {- return false, err- }- if !leftInfo.Mode().IsRegular() || !rightInfo.Mode().IsRegular() ||- leftInfo.Size() != rightInfo.Size() {- return false, nil+func accountDeclaredArchiveMember(+ name string, size int64, expanded *int64, limits archiveResourceLimits,+) error {+ if size < 0 {+ return fmt.Errorf("archive member has a negative declared size: %q", name)}- leftDigest, err := fileSHA256(left)- if err != nil {- return false, err+ if size > limits.memberBytes {+ return fmt.Errorf(+ "archive member %q exceeds the %d-byte expanded safety limit",+ name, limits.memberBytes,+ )}- rightDigest, err := fileSHA256(right)- if err != nil {- return false, err+ if *expanded > limits.expandedBytes-size {+ return fmt.Errorf(+ "archive exceeds the %d-byte aggregate expanded safety limit",+ limits.expandedBytes,+ )}- return leftDigest == rightDigest, nil+ *expanded += size+ return nil}-func installCandidateAtomically(src, dst string) error {- in, err := os.Open(src)- if err != nil {- return err- }- defer in.Close()- pattern := "." + filepath.Base(dst) + ".*.tmp"- if runtime.GOOS == "windows" {- pattern += ".exe"+func copyArchiveMemberWithLimits(+ destination io.Writer,+ source io.Reader,+ name string,+ declaredSize int64,+ actualExpanded *int64,+ limits archiveResourceLimits,+) error {+ remaining := limits.expandedBytes - *actualExpanded+ copyLimit := limits.memberBytes+ if remaining < copyLimit {+ copyLimit = remaining}- out, err := os.CreateTemp(filepath.Dir(dst), pattern)+ copied, err := io.Copy(+ destination, io.LimitReader(source, copyLimit+1),+ )if err != nil {return err}- staged := out.Name()- defer os.Remove(staged)- if _, err := io.Copy(out, in); err != nil {- out.Close()- return err- }- if err := out.Chmod(0755); err != nil {- out.Close()- return err- }- if err := out.Sync(); err != nil {- out.Close()- return err- }- if err := out.Close(); err != nil {- return err+ if copied > limits.memberBytes {+ return fmt.Errorf(+ "archive member %q exceeds the %d-byte actual expanded safety limit",+ name, limits.memberBytes,+ )}- if err := verifyCandidate(staged); err != nil {- return err+ if copied > remaining {+ return fmt.Errorf(+ "archive exceeds the %d-byte aggregate actual expanded safety limit",+ limits.expandedBytes,+ )}- if err := os.Rename(staged, dst); err != nil {- identical, compareErr := filesEqualSHA256(staged, dst)- if compareErr == nil && identical {- return verifyCandidate(dst)- }- return err+ if copied != declaredSize {+ return fmt.Errorf(+ "archive member %q actual size %d does not match declared size %d",+ name, copied, declaredSize,+ )}+ *actualExpanded += copiedreturn nil}-func windowsPairToken() (string, error) {- raw := make([]byte, windowsPairTransactionTagSize)- if _, err := rand.Read(raw); err != nil {- return "", err- }- return hex.EncodeToString(raw), nil+func tarGzMemberNames(archivePath string) ([]string, error) {+ return tarGzMemberNamesWithLimits(+ archivePath, defaultArchiveResourceLimits,+ )}-func windowsPairLockOwner(lockPath string) (int, string, bool) {- data, err := os.ReadFile(filepath.Join(lockPath, windowsPairLockOwnerFile))- if err != nil {- return 0, "", false+func tarGzMemberNamesWithLimits(+ archivePath string, limits archiveResourceLimits,+) ([]string, error) {+ if err := validateArchiveResourceLimits(limits); err != nil {+ return nil, err}- var pid int- var token string- var extra string- count, _ := fmt.Sscanf(string(data), "%d %s %s", &pid, &token, &extra)- decoded, decodeErr := hex.DecodeString(token)- if count != 2 || pid <= 0 || decodeErr != nil ||- len(decoded) != windowsPairTransactionTagSize {- return 0, "", false+ if err := requireCompressedArchiveWithinLimit(archivePath, limits); err != nil {+ return nil, err}- return pid, token, true-}--func windowsPairTryReclaimLock(lockPath, contenderToken string) bool {- pid, _, ownerOK := windowsPairLockOwner(lockPath)- reclaim := ownerOK && !cbmWindowsLockProcessAlive(pid)- if !ownerOK {- status, err := os.Stat(lockPath)- if os.IsNotExist(err) {- return true- }- if err != nil {- return false+ f, err := os.Open(archivePath)+ if err != nil {+ return nil, err+ }+ defer f.Close()+ gz, err := gzip.NewReader(f)+ if err != nil {+ return nil, err+ }+ defer gz.Close()+ tr := tar.NewReader(gz)+ var names []string+ var declaredExpanded int64+ for {+ hdr, err := tr.Next()+ if err == io.EOF {+ break+ }+ if err != nil {+ return nil, err+ }+ if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA {+ return nil, fmt.Errorf(+ "archive member is not a regular root file: %q", hdr.Name,+ )+ }+ if len(names) >= limits.members {+ return nil, fmt.Errorf(+ "archive exceeds the %d-member safety limit", limits.members,+ )+ }+ if err := accountDeclaredArchiveMember(+ hdr.Name, hdr.Size, &declaredExpanded, limits,+ ); err != nil {+ return nil, err+ }+ names = append(names, hdr.Name)+ }+ return names, nil+}++func extractTarGz(+ archivePath, destDir string,+ archiveNames, extractNames []string,+ variant string,+) ([]string, error) {+ return extractTarGzWithLimits(+ archivePath,+ destDir,+ archiveNames,+ extractNames,+ variant,+ defaultArchiveResourceLimits,+ )+}++func extractTarGzWithLimits(+ archivePath, destDir string,+ archiveNames, extractNames []string,+ variant string,+ limits archiveResourceLimits,+) ([]string, error) {+ names, err := tarGzMemberNamesWithLimits(archivePath, limits)+ if err != nil {+ return nil, err+ }+ uiPack, err := validateArchiveMemberNames(+ names, archiveNames, variant, false,+ )+ if err != nil {+ return nil, err+ }+ runtimeNames := runtimeArchiveNames(extractNames, uiPack)+ targets := make(map[string]struct{}, len(runtimeNames))+ for _, name := range runtimeNames {+ targets[name] = struct{}{}+ }++ f, err := os.Open(archivePath)+ if err != nil {+ return nil, err+ }+ defer f.Close()+ gz, err := gzip.NewReader(f)+ if err != nil {+ return nil, err+ }+ defer gz.Close()+ tr := tar.NewReader(gz)+ extracted := make(map[string]struct{}, len(runtimeNames))+ memberCount := 0+ var declaredExpanded int64+ var actualExpanded int64+ for {+ hdr, err := tr.Next()+ if err == io.EOF {+ break+ }+ if err != nil {+ return nil, err+ }+ memberCount+++ if memberCount > limits.members {+ return nil, fmt.Errorf(+ "archive exceeds the %d-member safety limit", limits.members,+ )+ }+ if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA {+ return nil, fmt.Errorf(+ "archive member is not a regular root file: %q", hdr.Name,+ )+ }+ if err := accountDeclaredArchiveMember(+ hdr.Name, hdr.Size, &declaredExpanded, limits,+ ); err != nil {+ return nil, err+ }+ if _, wanted := targets[hdr.Name]; wanted {+ outputPath := filepath.Join(destDir, hdr.Name)+ out, err := os.OpenFile(+ outputPath,+ os.O_WRONLY|os.O_CREATE|os.O_EXCL,+ 0600,+ )+ if err != nil {+ return nil, err+ }+ copyErr := copyArchiveMemberWithLimits(+ out, tr, hdr.Name, hdr.Size, &actualExpanded, limits,+ )+ closeErr := out.Close()+ if copyErr != nil {+ _ = os.Remove(outputPath)+ return nil, copyErr+ }+ if closeErr != nil {+ _ = os.Remove(outputPath)+ return nil, closeErr+ }+ extracted[hdr.Name] = struct{}{}+ } else if err := copyArchiveMemberWithLimits(+ io.Discard, tr, hdr.Name, hdr.Size, &actualExpanded, limits,+ ); err != nil {+ return nil, err+ }+ }+ if len(extracted) != len(runtimeNames) {+ return nil, fmt.Errorf("archive runtime set extraction was incomplete")+ }+ return runtimeNames, nil+}++func extractZip(+ archivePath, destDir string,+ archiveNames, extractNames []string,+ variant string,+) ([]string, error) {+ return extractZipWithLimits(+ archivePath,+ destDir,+ archiveNames,+ extractNames,+ variant,+ defaultArchiveResourceLimits,+ )+}++func extractZipWithLimits(+ archivePath, destDir string,+ archiveNames, extractNames []string,+ variant string,+ limits archiveResourceLimits,+) ([]string, error) {+ if err := validateArchiveResourceLimits(limits); err != nil {+ return nil, err+ }+ if err := requireCompressedArchiveWithinLimit(archivePath, limits); err != nil {+ return nil, err+ }+ r, err := zip.OpenReader(archivePath)+ if err != nil {+ return nil, err+ }+ defer r.Close()+ if len(r.File) > limits.members {+ return nil, fmt.Errorf(+ "archive exceeds the %d-member safety limit", limits.members,+ )+ }+ names := make([]string, 0, len(r.File))+ declaredSizes := make(map[string]int64, len(r.File))+ var declaredExpanded int64+ for _, f := range r.File {+ name, err := validateWindowsZipMember(f.Name)+ if err != nil {+ return nil, err+ }+ if !f.FileInfo().Mode().IsRegular() {+ return nil, fmt.Errorf(+ "archive member is not a regular root file: %q", f.Name,+ )+ }+ if f.UncompressedSize64 > uint64(limits.memberBytes) {+ return nil, fmt.Errorf(+ "archive member %q exceeds the %d-byte expanded safety limit",+ name, limits.memberBytes,+ )+ }+ declaredSize := int64(f.UncompressedSize64)+ if err := accountDeclaredArchiveMember(+ name, declaredSize, &declaredExpanded, limits,+ ); err != nil {+ return nil, err+ }+ names = append(names, name)+ declaredSizes[name] = declaredSize+ }+ uiPack, err := validateArchiveMemberNames(+ names, archiveNames, variant, true,+ )+ if err != nil {+ return nil, err+ }+ runtimeNames := runtimeArchiveNames(extractNames, uiPack)+ targetNames := make(map[string]struct{}, len(runtimeNames))+ for _, name := range runtimeNames {+ targetNames[name] = struct{}{}+ }+ extracted := make(map[string]struct{}, len(runtimeNames))+ var actualExpanded int64++ for index, target := range r.File {+ name := names[index]+ rc, err := target.Open()+ if err != nil {+ return nil, err+ }+ var destination io.Writer = io.Discard+ var out *os.File+ outputPath := ""+ if _, wanted := targetNames[name]; wanted {+ outputPath = filepath.Join(destDir, name)+ out, err = os.OpenFile(+ outputPath,+ os.O_WRONLY|os.O_CREATE|os.O_EXCL,+ 0600,+ )+ if err != nil {+ _ = rc.Close()+ return nil, err+ }+ destination = out+ }+ copyErr := copyArchiveMemberWithLimits(+ destination,+ rc,+ name,+ declaredSizes[name],+ &actualExpanded,+ limits,+ )+ var closeOutErr error+ if out != nil {+ closeOutErr = out.Close()+ }+ closeReadErr := rc.Close()+ if copyErr != nil {+ if outputPath != "" {+ _ = os.Remove(outputPath)+ }+ return nil, copyErr+ }+ if closeOutErr != nil {+ _ = os.Remove(outputPath)+ return nil, closeOutErr+ }+ if closeReadErr != nil {+ if outputPath != "" {+ _ = os.Remove(outputPath)+ }+ return nil, closeReadErr+ }+ if outputPath != "" {+ extracted[name] = struct{}{}+ }+ }+ if len(extracted) != len(runtimeNames) {+ return nil, fmt.Errorf("archive runtime set extraction was incomplete")+ }+ return runtimeNames, nil+}++func validateWindowsZipMember(raw string) (string, error) {+ name := strings.ReplaceAll(raw, "\\", "/")+ segmentsName := strings.TrimSuffix(name, "/")+ if segmentsName == "" || strings.HasPrefix(name, "/") || strings.Contains(name, ":") {+ return "", fmt.Errorf("unsafe zip entry path: %q", raw)+ }+ for _, segment := range strings.Split(segmentsName, "/") {+ if segment == "" || segment == "." || segment == ".." ||+ strings.HasSuffix(segment, ".") || strings.HasSuffix(segment, " ") {+ return "", fmt.Errorf("unsafe zip entry path: %q", raw)+ }+ }+ return name, nil+}++func verifyCandidate(path string) error {+ ctx, cancel := context.WithTimeout(context.Background(), candidateTimeout)+ defer cancel()+ cmd := exec.CommandContext(ctx, path, "--verify-runtime-assets")+ cmd.Stdin = nil+ cmd.Stdout = io.Discard+ cmd.Stderr = io.Discard+ if err := cmd.Run(); err != nil {+ if ctx.Err() != nil {+ return fmt.Errorf("downloaded binary verification timed out: %w", ctx.Err())+ }+ return fmt.Errorf("downloaded binary failed to run: %w", err)+ }+ return nil+}++func fileSHA256(path string) ([sha256.Size]byte, error) {+ var digest [sha256.Size]byte+ source, err := os.Open(path)+ if err != nil {+ return digest, err+ }+ defer source.Close()+ hash := sha256.New()+ if _, err := io.Copy(hash, source); err != nil {+ return digest, err+ }+ copy(digest[:], hash.Sum(nil))+ return digest, nil+}++func filesEqualSHA256(left, right string) (bool, error) {+ leftInfo, err := os.Lstat(left)+ if err != nil {+ return false, err+ }+ rightInfo, err := os.Lstat(right)+ if err != nil {+ return false, err+ }+ if !leftInfo.Mode().IsRegular() || !rightInfo.Mode().IsRegular() ||+ !platformRuntimeSetFileLinkCountOne(left, leftInfo) ||+ !platformRuntimeSetFileLinkCountOne(right, rightInfo) ||+ leftInfo.Size() != rightInfo.Size() {+ return false, nil+ }+ leftDigest, err := fileSHA256(left)+ if err != nil {+ return false, err+ }+ rightDigest, err := fileSHA256(right)+ if err != nil {+ return false, err+ }+ return leftDigest == rightDigest, nil+}++func regularRuntimeFile(path string) bool {+ status, err := os.Lstat(path)+ return err == nil && status.Mode().IsRegular() &&+ platformRuntimeSetFileLinkCountOne(path, status)+}++func uiPackMatchesDigest(directory, name string) bool {+ digest, err := fileSHA256(filepath.Join(directory, name))+ if err != nil {+ return false+ }+ expected := strings.TrimSuffix(strings.TrimPrefix(name, "cbm-ui-"), ".pack")+ return hex.EncodeToString(digest[:]) == expected+}++func runtimeSetNames(+ directory, binaryName, variant string,+) ([]string, bool) {+ if !regularRuntimeFile(filepath.Join(directory, binaryName)) ||+ !regularRuntimeFile(filepath.Join(directory, integrationsFileName)) {+ return nil, false+ }+ entries, err := os.ReadDir(directory)+ if err != nil {+ return nil, false+ }+ var packLike []string+ var validPacks []string+ for _, entry := range entries {+ name := entry.Name()+ if strings.HasPrefix(name, "cbm-ui-") && strings.HasSuffix(name, ".pack") {+ packLike = append(packLike, name)+ if isUIPackName(name) &&+ regularRuntimeFile(filepath.Join(directory, name)) &&+ uiPackMatchesDigest(directory, name) {+ validPacks = append(validPacks, name)+ }+ }+ }+ if variant == "ui" {+ if len(packLike) != 1 || len(validPacks) != 1 {+ return nil, false+ }+ } else if len(packLike) != 0 {+ return nil, false+ }+ names := []string{integrationsFileName}+ if variant == "ui" {+ names = append(names, validPacks[0])+ }+ names = append(names, binaryName)+ return names, true+}++func runtimeSetReady(+ directory, binaryName, variant string, verifier func(string) error,+) bool {+ if _, ok := runtimeSetNames(directory, binaryName, variant); !ok {+ return false+ }+ return verifier == nil || verifier(filepath.Join(directory, binaryName)) == nil+}++func requireSafeRuntimeDirectory(directory string) error {+ status, err := os.Lstat(directory)+ if err != nil {+ return err+ }+ if !status.IsDir() || status.Mode()&os.ModeSymlink != 0 {+ return fmt.Errorf("refusing unsafe package-cache directory: %s", directory)+ }+ return nil+}++func runtimeSetReadyLocked(+ directory, binaryName, variant string, verifier func(string) error,+) (ready bool, result error) {+ if err := os.MkdirAll(directory, 0755); err != nil {+ return false, err+ }+ if err := requireSafeRuntimeDirectory(directory); err != nil {+ return false, err+ }+ lock, err := acquireRuntimeSetLock(directory)+ if err != nil {+ return false, err+ }+ defer func() {+ attachRuntimeLockReleaseError(&result, releaseRuntimeSetLock(lock))+ }()+ if err := refreshRuntimeSetLock(lock); err != nil {+ return false, err+ }+ if err := reconcileRuntimeBackups(+ directory, binaryName, variant, verifier, lock,+ ); err != nil {+ return false, err+ }+ return runtimeSetReady(directory, binaryName, variant, verifier), nil+}++func copyRuntimeStage(+ sourcePath, destinationDirectory string, executable bool,+ maintainLease func() error,+) (string, error) {+ input, err := os.Open(sourcePath)+ if err != nil {+ return "", err+ }+ defer input.Close()+ pattern := ".cbm-runtime-stage-*"+ if executable && runtime.GOOS == "windows" {+ pattern += ".exe"+ }+ output, err := os.CreateTemp(destinationDirectory, pattern)+ if err != nil {+ return "", err+ }+ stagedPath := output.Name()+ mode := os.FileMode(0644)+ if executable {+ mode = 0755+ }+ buffer := make([]byte, 1024*1024)+ lastRefresh := time.Now()+ var copyErr error+ for {+ count, readErr := input.Read(buffer)+ if count > 0 {+ written := 0+ for written < count {+ amount, writeErr := output.Write(buffer[written:count])+ if writeErr != nil {+ copyErr = writeErr+ break+ }+ written += amount+ }+ }+ if copyErr != nil || readErr == io.EOF {+ break+ }+ if readErr != nil {+ copyErr = readErr+ break+ }+ if maintainLease != nil && time.Since(lastRefresh) >= runtimeSetLockHeartbeat {+ if err := maintainLease(); err != nil {+ copyErr = err+ break+ }+ lastRefresh = time.Now()+ }+ }+ chmodErr := output.Chmod(mode)+ syncErr := output.Sync()+ closeErr := output.Close()+ for _, candidate := range []error{copyErr, chmodErr, syncErr, closeErr} {+ if candidate != nil {+ _ = os.Remove(stagedPath)+ return "", candidate+ }+ }+ return stagedPath, nil+}++// A grouped backup is a small process-crash journal. runtimeBackupRetired+// separates a partial retirement from partial publication;+// runtimeBackupCleanupOnly makes deletion retryable after the destination has+// been accepted or restored.+func runtimeBackupDirectoryName(name string) bool {+ if !strings.HasPrefix(name, runtimeBackupPrefix) {+ return false+ }+ token := strings.TrimPrefix(name, runtimeBackupPrefix)+ decoded, err := hex.DecodeString(token)+ return err == nil && token == strings.ToLower(token) &&+ len(decoded) == runtimeSetLockTokenSize+}++func runtimeBackupTargetName(name, binaryName string) bool {+ return name == binaryName || name == integrationsFileName ||+ (strings.HasPrefix(name, "cbm-ui-") && strings.HasSuffix(name, ".pack"))+}++func createRuntimeBackupDirectory(directory string) (string, error) {+ for attempt := 0; attempt < 128; attempt++ {+ token, err := runtimeSetLockToken()+ if err != nil {+ return "", err+ }+ backupDirectory := filepath.Join(directory, runtimeBackupPrefix+token)+ if err := os.Mkdir(backupDirectory, 0700); err == nil {+ return backupDirectory, nil+ } else if !os.IsExist(err) {+ return "", err+ }+ }+ return "", fmt.Errorf("could not reserve a package-cache backup transaction")+}++func createRuntimeBackupMarker(backupDirectory, name string) error {+ marker, err := os.OpenFile(+ filepath.Join(backupDirectory, name),+ os.O_WRONLY|os.O_CREATE|os.O_EXCL,+ 0600,+ )+ if err != nil {+ return err+ }+ syncErr := marker.Sync()+ closeErr := marker.Close()+ if syncErr != nil {+ return syncErr+ }+ return closeErr+}++func inspectRuntimeBackupDirectory(+ directory, entryName, binaryName string,+) (*runtimeBackupTransaction, error) {+ backupDirectory := filepath.Join(directory, entryName)+ directoryStatus, err := os.Lstat(backupDirectory)+ if err != nil || !directoryStatus.IsDir() ||+ directoryStatus.Mode()&os.ModeSymlink != 0 {+ return nil, fmt.Errorf(+ "refusing unsafe package-cache backup: %s", backupDirectory,+ )+ }+ backup := &runtimeBackupTransaction{+ path: backupDirectory, files: make(map[string]runtimeBackupFile),+ }+ entries, err := os.ReadDir(backupDirectory)+ if err != nil {+ return nil, err+ }+ for _, entry := range entries {+ name := entry.Name()+ candidate := filepath.Join(backupDirectory, name)+ status, err := os.Lstat(candidate)+ if err != nil {+ return nil, err+ }+ if name == runtimeBackupRetired || name == runtimeBackupCleanupOnly {+ if !status.Mode().IsRegular() ||+ !platformRuntimeSetFileLinkCountOne(candidate, status) ||+ status.Size() != 0 {+ return nil, fmt.Errorf(+ "refusing unsafe package-cache backup marker: %s", candidate,+ )+ }+ if name == runtimeBackupRetired {+ backup.retired = true+ } else {+ backup.cleanupOnly = true+ }+ continue+ }+ if !runtimeBackupTargetName(name, binaryName) ||+ !status.Mode().IsRegular() ||+ !platformRuntimeSetFileLinkCountOne(candidate, status) {+ return nil, fmt.Errorf(+ "refusing unsafe package-cache backup member: %s", candidate,+ )+ }+ digest, err := fileSHA256(candidate)+ if err != nil {+ return nil, err+ }+ backup.files[name] = runtimeBackupFile{path: candidate, digest: digest}+ }+ return backup, nil+}++func listRuntimeBackupDirectories(+ directory, binaryName string,+) ([]*runtimeBackupTransaction, error) {+ entries, err := os.ReadDir(directory)+ if err != nil {+ return nil, err+ }+ var names []string+ for _, entry := range entries {+ if runtimeBackupDirectoryName(entry.Name()) {+ names = append(names, entry.Name())+ }+ }+ sort.Strings(names)+ backups := make([]*runtimeBackupTransaction, 0, len(names))+ for _, name := range names {+ backup, err := inspectRuntimeBackupDirectory(directory, name, binaryName)+ if err != nil {+ return nil, err+ }+ backups = append(backups, backup)+ }+ return backups, nil+}++func currentRuntimeTargets(+ directory, binaryName string,+) (map[string]string, error) {+ entries, err := os.ReadDir(directory)+ if err != nil {+ return nil, err+ }+ targets := make(map[string]string)+ for _, entry := range entries {+ name := entry.Name()+ if !runtimeBackupTargetName(name, binaryName) {+ continue+ }+ target := filepath.Join(directory, name)+ status, err := os.Lstat(target)+ if err != nil || !status.Mode().IsRegular() ||+ !platformRuntimeSetFileLinkCountOne(target, status) {+ return nil, fmt.Errorf("refusing unsafe package-cache target: %s", target)+ }+ targets[name] = target+ }+ return targets, nil+}++func cleanupRuntimeBackup(+ backup *runtimeBackupTransaction, lock *runtimeSetLock,+) error {+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err+ }+ if !backup.cleanupOnly {+ if err := createRuntimeBackupMarker(+ backup.path, runtimeBackupCleanupOnly,+ ); err != nil {+ return err+ }+ backup.cleanupOnly = true+ }+ names := make([]string, 0, len(backup.files))+ for name := range backup.files {+ names = append(names, name)+ }+ sort.Strings(names)+ for _, name := range names {+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err+ }+ member := backup.files[name]+ if !pathMatchesSHA256(member.path, member.digest) {+ return fmt.Errorf(+ "package-cache backup member changed during cleanup: %s", name,+ )+ }+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err+ }+ if err := os.Remove(member.path); err != nil {+ return err+ }+ if runtimeBackupCrashObserver != nil {+ if err := runtimeBackupCrashObserver(+ runtimeBackupCleanupRemovedEvent, member.path,+ ); err != nil {+ return err+ }+ }+ }+ if backup.retired {+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err+ }+ if err := os.Remove(filepath.Join(backup.path, runtimeBackupRetired)); err != nil {+ return err+ }+ }+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err+ }+ if err := os.Remove(filepath.Join(backup.path, runtimeBackupCleanupOnly)); err != nil {+ return err+ }+ return os.Remove(backup.path)+}++func copyRuntimeBackupFile(+ member runtimeBackupFile, target string, executable bool, lock *runtimeSetLock,+) error {+ staged, err := copyRuntimeStage(+ member.path,+ filepath.Dir(target),+ executable,+ func() error { return refreshRuntimeSetLock(lock) },+ )+ if err != nil {+ return err+ }+ defer os.Remove(staged)+ stagedDigest, err := fileSHA256(staged)+ if err != nil {+ return err+ }+ if stagedDigest != member.digest {+ return fmt.Errorf("package-cache backup changed while it was being restored")+ }+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err+ }+ return os.Rename(staged, target)+}++func reconcileRuntimeBackups(+ directory, binaryName, variant string,+ verifier func(string) error,+ lock *runtimeSetLock,+) error {+ if err := refreshRuntimeSetLock(lock); err != nil {+ return err+ }+ backups, err := listRuntimeBackupDirectories(directory, binaryName)+ if err != nil {+ return err+ }+ remaining := make([]*runtimeBackupTransaction, 0, len(backups))+ for _, backup := range backups {+ if backup.cleanupOnly {+ if err := cleanupRuntimeBackup(backup, lock); err != nil {+ return err+ }+ } else {+ remaining = append(remaining, backup)+ }+ }+ backups = remaining+ if len(backups) == 0 {+ return nil+ }+ if runtimeSetReady(directory, binaryName, variant, verifier) {+ for _, backup := range backups {+ if err := cleanupRuntimeBackup(backup, lock); err != nil {+ return err+ }+ }+ return nil+ }+ if len(backups) == 0 {+ return nil+ }+ remaining = remaining[:0]+ for _, backup := range backups {+ if !backup.retired && len(backup.files) == 0 {+ if err := cleanupRuntimeBackup(backup, lock); err != nil {+ return err+ }+ } else {+ remaining = append(remaining, backup)+ }+ }+ backups = remaining+ if len(backups) == 0 {+ return nil+ }+ if len(backups) != 1 {+ return fmt.Errorf(+ "multiple package-cache backup transactions require manual recovery",+ )+ }+ backup := backups[0]+ targets, err := currentRuntimeTargets(directory, binaryName)+ if err != nil {+ return err+ }+ if !backup.retired {+ for name, member := range backup.files {+ if target, exists := targets[name]; exists &&+ !pathMatchesSHA256(target, member.digest) {+ return fmt.Errorf(+ "package-cache backup conflicts with current target: %s", name,+ )+ }+ }+ } else {+ if target, exists := targets[binaryName]; exists {+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err+ }+ if err := os.Remove(target); err != nil {+ return err+ }+ delete(targets, binaryName)+ }+ names := make([]string, 0, len(targets))+ for name := range targets {+ names = append(names, name)+ }+ sort.Strings(names)+ for _, name := range names {+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err+ }+ if err := os.Remove(targets[name]); err != nil {+ return err+ }+ }+ }+ restoreNames := make([]string, 0, len(backup.files))+ for name := range backup.files {+ if name != binaryName {+ restoreNames = append(restoreNames, name)+ }+ }+ sort.Strings(restoreNames)+ if _, exists := backup.files[binaryName]; exists {+ restoreNames = append(restoreNames, binaryName)+ }+ for _, name := range restoreNames {+ member := backup.files[name]+ target := filepath.Join(directory, name)+ if !pathMatchesSHA256(target, member.digest) {+ if err := copyRuntimeBackupFile(+ member, target, name == binaryName, lock,+ ); err != nil {+ return err+ }+ }+ }+ for name, member := range backup.files {+ if !pathMatchesSHA256(filepath.Join(directory, name), member.digest) {+ return fmt.Errorf("package-cache backup restoration failed: %s", name)+ }+ }+ if err := cleanupRuntimeBackup(backup, lock); err != nil {+ return err+ }+ return nil+}++func pathMatchesSHA256(path string, expected [sha256.Size]byte) bool {+ if !regularRuntimeFile(path) {+ return false+ }+ actual, err := fileSHA256(path)+ return err == nil && actual == expected+}++func runtimeSetLockToken() (string, error) {+ raw := make([]byte, runtimeSetLockTokenSize)+ if _, err := rand.Read(raw); err != nil {+ return "", err+ }+ return hex.EncodeToString(raw), nil+}++func runtimeSetLockOwner(lockPath string) (runtimeSetLockOwnerRecord, bool) {+ var empty runtimeSetLockOwnerRecord+ status, err := os.Lstat(lockPath)+ if err != nil || status.Mode()&os.ModeSymlink != 0 ||+ (!status.Mode().IsRegular() && !status.IsDir()) {+ return empty, false+ }+ ownerPath := lockPath+ if status.IsDir() {+ ownerPath = filepath.Join(lockPath, runtimeSetLockOwnerFile)+ }+ ownerStatus, err := os.Lstat(ownerPath)+ if err != nil || !ownerStatus.Mode().IsRegular() {+ return empty, false+ }+ data, err := os.ReadFile(ownerPath)+ if err != nil {+ return empty, false+ }+ var record runtimeSetLockOwnerRecord+ if err := json.Unmarshal(data, &record); err != nil {+ return empty, false+ }+ decoded, decodeErr := hex.DecodeString(record.Token)+ if record.PID <= 0 || record.Token != strings.ToLower(record.Token) ||+ decodeErr != nil || len(decoded) != runtimeSetLockTokenSize {+ return empty, false+ }+ return record, true+}++func runtimeSetSameLockObject(left, right os.FileInfo) bool {+ return left != nil && right != nil && os.SameFile(left, right) &&+ left.Mode().Type() == right.Mode().Type()+}++func writeRuntimeSetLockRecord(owner *os.File, token string) error {+ if err := owner.Truncate(0); err != nil {+ return err+ }+ if _, err := owner.Seek(0, io.SeekStart); err != nil {+ return err+ }+ if err := json.NewEncoder(owner).Encode(runtimeSetLockOwnerRecord{+ PID: os.Getpid(),+ Token: token,+ LeaseExpires: time.Now().Add(runtimeSetLockLease).UnixMilli(),+ }); err != nil {+ return err+ }+ return owner.Sync()+}++// writeRuntimeSetLockOwner creates the legacy directory-owner shape used by+// migration tests and previous wrapper releases.+func writeRuntimeSetLockOwner(lockPath, token string) error {+ owner, err := os.OpenFile(+ filepath.Join(lockPath, runtimeSetLockOwnerFile),+ os.O_WRONLY|os.O_CREATE|os.O_EXCL,+ 0600,+ )+ if err != nil {+ return err+ }+ writeErr := json.NewEncoder(owner).Encode(runtimeSetLockOwnerRecord{+ PID: os.Getpid(), Token: token,+ })+ syncErr := owner.Sync()+ closeErr := owner.Close()+ for _, candidate := range []error{writeErr, syncErr, closeErr} {+ if candidate != nil {+ return candidate}- reclaim = time.Since(status.ModTime()) >= windowsPairOwnerlessStale}- if !reclaim {+ return nil+}++func runtimeSetOwnerReclaimable(+ status os.FileInfo, owner runtimeSetLockOwnerRecord, ownerOK bool,+) bool {+ if ownerOK {+ // Lease expiry and age are not evidence that a syntactically valid+ // owner is dead. A paused live publisher can resume between lock-owner+ // assertions, so reclaim only when the platform proves its PID is gone.+ return !runtimeSetProcessAlive(owner.PID)+ }+ return time.Since(status.ModTime()) >= runtimeSetOwnerlessStale+}++func restoreDisplacedRuntimeSetLock(reclaimed, lockPath string, status os.FileInfo) {+ if status == nil || !status.Mode().IsRegular() {+ return+ }+ if err := os.Link(reclaimed, lockPath); err == nil {+ _ = os.Remove(reclaimed)+ }+}++func runtimeSetTryReclaimLock(lockPath, contenderToken string) bool {+ observedStatus, err := os.Lstat(lockPath)+ if os.IsNotExist(err) {+ return true+ }+ if err != nil || observedStatus.Mode()&os.ModeSymlink != 0 ||+ (!observedStatus.Mode().IsRegular() && !observedStatus.IsDir()) {+ return false+ }+ owner, ownerOK := runtimeSetLockOwner(lockPath)+ if !runtimeSetOwnerReclaimable(observedStatus, owner, ownerOK) {return false}reclaimed := lockPath + ".reclaimed-" + contenderTokenif err := os.Rename(lockPath, reclaimed); err != nil {return os.IsNotExist(err)}- _ = os.RemoveAll(reclaimed)+ movedStatus, movedErr := os.Lstat(reclaimed)+ if movedErr != nil || !runtimeSetSameLockObject(observedStatus, movedStatus) {+ restoreDisplacedRuntimeSetLock(reclaimed, lockPath, movedStatus)+ return false+ }+ movedOwner, movedOwnerOK := runtimeSetLockOwner(reclaimed)+ if !runtimeSetOwnerReclaimable(movedStatus, movedOwner, movedOwnerOK) {+ restoreDisplacedRuntimeSetLock(reclaimed, lockPath, movedStatus)+ return false+ }+ if movedStatus.IsDir() {+ _ = os.RemoveAll(reclaimed)+ } else {+ _ = os.Remove(reclaimed)+ }return true}-func acquireWindowsPairLock(dstDir string) (*windowsPairLock, error) {- token, err := windowsPairToken()+func assertRuntimeSetLockOwner(lock *runtimeSetLock) error {+ if lock == nil || lock.file == nil {+ return fmt.Errorf("missing package-cache runtime-set publication lock")+ }+ descriptorStatus, descriptorErr := lock.file.Stat()+ canonicalStatus, canonicalErr := os.Lstat(lock.path)+ owner, ownerOK := runtimeSetLockOwner(lock.path)+ if descriptorErr != nil || canonicalErr != nil ||+ !runtimeSetSameLockObject(descriptorStatus, canonicalStatus) ||+ !ownerOK || owner.PID != os.Getpid() || owner.Token != lock.token {+ return fmt.Errorf(+ "package-cache runtime-set publication lock ownership changed",+ )+ }+ return nil+}++func refreshRuntimeSetLock(lock *runtimeSetLock) error {+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err+ }+ if err := writeRuntimeSetLockRecord(lock.file, lock.token); err != nil {+ return err+ }+ return assertRuntimeSetLockOwner(lock)+}++func acquireRuntimeSetLock(destinationDirectory string) (*runtimeSetLock, error) {+ token, err := runtimeSetLockToken()if err != nil {return nil, err}- lockPath := filepath.Join(dstDir, windowsPairLockName)- deadline := time.Now().Add(windowsPairLockWait)+ lockPath := filepath.Join(destinationDirectory, runtimeSetLockName)+ claimPath := lockPath + ".claim-" + token+ deadline := time.Now().Add(runtimeSetLockWait)for {- if err := os.Mkdir(lockPath, 0700); err == nil {- owner := []byte(fmt.Sprintf("%d %s\n", os.Getpid(), token))- ownerPath := filepath.Join(lockPath, windowsPairLockOwnerFile)- if err := os.WriteFile(ownerPath, owner, 0600); err != nil {- _ = os.RemoveAll(lockPath)+ owner, claimErr := os.OpenFile(+ claimPath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600,+ )+ if claimErr != nil {+ return nil, claimErr+ }+ if err := writeRuntimeSetLockRecord(owner, token); err != nil {+ _ = owner.Close()+ _ = os.Remove(claimPath)+ return nil, err+ }+ if runtimeSetLockClaimObserver != nil {+ if err := runtimeSetLockClaimObserver(); err != nil {+ _ = owner.Close()+ _ = os.Remove(claimPath)return nil, err}- return &windowsPairLock{path: lockPath, token: token}, nil- } else if !os.IsExist(err) {- return nil, err}- if windowsPairTryReclaimLock(lockPath, token) {+ linkErr := os.Link(claimPath, lockPath)+ if linkErr == nil {+ if err := os.Remove(claimPath); err != nil {+ _ = owner.Close()+ return nil, err+ }+ descriptorStatus, descriptorErr := owner.Stat()+ canonicalStatus, canonicalErr := os.Lstat(lockPath)+ if descriptorErr != nil || canonicalErr != nil ||+ !runtimeSetSameLockObject(descriptorStatus, canonicalStatus) {+ _ = owner.Close()+ return nil, fmt.Errorf(+ "package-cache runtime-set publication lock ownership changed",+ )+ }+ return &runtimeSetLock{path: lockPath, token: token, file: owner}, nil+ }+ _ = owner.Close()+ _ = os.Remove(claimPath)+ if !os.IsExist(linkErr) {+ return nil, linkErr+ }+ if runtimeSetTryReclaimLock(lockPath, token) {continue}+ if runtimeSetLockWaitObserver != nil {+ runtimeSetLockWaitObserver()+ }if !time.Now().Before(deadline) {return nil, fmt.Errorf(- "timed out waiting for Windows package-cache publication lock")+ "timed out waiting for package-cache runtime-set publication lock",+ )}- time.Sleep(windowsPairLockPoll)+ time.Sleep(runtimeSetLockPoll)}}-func releaseWindowsPairLock(lock *windowsPairLock) error {- if lock == nil {- return fmt.Errorf("missing Windows package-cache publication lock")- }- pid, token, ok := windowsPairLockOwner(lock.path)- if !ok || pid != os.Getpid() || token != lock.token {- return fmt.Errorf("Windows package-cache publication lock ownership changed")- }- if err := os.Remove(filepath.Join(lock.path, windowsPairLockOwnerFile)); err != nil {+func releaseRuntimeSetLock(lock *runtimeSetLock) error {+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ if lock != nil && lock.file != nil {+ _ = lock.file.Close()+ }return err}- return os.Remove(lock.path)-}--func windowsPairReady(dstDir string, verifier func(string) error) bool {- launcher := filepath.Join(dstDir, windowsLauncherName)- payload := filepath.Join(dstDir, windowsPayloadName)- launcherStatus, launcherErr := os.Lstat(launcher)- payloadStatus, payloadErr := os.Lstat(payload)- return launcherErr == nil && payloadErr == nil &&- launcherStatus.Mode().IsRegular() && payloadStatus.Mode().IsRegular() &&- verifier(launcher) == nil-}--func copyWindowsPairStage(src, dst string) error {- input, err := os.Open(src)- if err != nil {+ released := lock.path + ".released-" + lock.token+ if err := os.Rename(lock.path, released); err != nil {+ _ = lock.file.Close()return err}- output, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)- if err != nil {- _ = input.Close()- return err+ descriptorStatus, descriptorErr := lock.file.Stat()+ releasedStatus, releasedErr := os.Lstat(released)+ owner, ownerOK := runtimeSetLockOwner(released)+ if descriptorErr != nil || releasedErr != nil ||+ !runtimeSetSameLockObject(descriptorStatus, releasedStatus) ||+ !ownerOK || owner.PID != os.Getpid() || owner.Token != lock.token {+ restoreDisplacedRuntimeSetLock(released, lock.path, releasedStatus)+ _ = lock.file.Close()+ return fmt.Errorf(+ "package-cache runtime-set publication lock ownership changed",+ )}- _, copyErr := io.Copy(output, input)- closeInputErr := input.Close()- chmodErr := output.Chmod(0755)- syncErr := output.Sync()- closeOutputErr := output.Close()- for _, candidate := range []error{- copyErr, closeInputErr, chmodErr, syncErr, closeOutputErr,- } {- if candidate != nil {- return candidate- }+ removeErr := os.Remove(released)+ closeErr := lock.file.Close()+ if removeErr != nil {+ return removeErr}- return nil+ return closeErr}-func pathMatchesSHA256(path string, expected [sha256.Size]byte) bool {- status, err := os.Lstat(path)- if err != nil || !status.Mode().IsRegular() {- return false+func attachRuntimeLockReleaseError(result *error, releaseErr error) {+ if releaseErr == nil {+ return}- actual, err := fileSHA256(path)- return err == nil && actual == expected+ if *result == nil {+ *result = releaseErr+ return+ }+ *result = fmt.Errorf("%v; runtime lock release failed: %w", *result, releaseErr)}-func installWindowsPairAtomicallyWithVerifier(- srcDir, dstDir string, verifier func(string) error,+func publishRuntimeSetWithRecoveryAndRenamer(+ sourceDirectory, destinationDirectory, binaryName, variant string,+ verifier func(string) error,+ renameFile func(string, string) error,) (result error) {- names := []string{windowsLauncherName, windowsPayloadName}- if err := verifier(filepath.Join(srcDir, windowsLauncherName)); err != nil {- return fmt.Errorf("source Windows release pair failed verification: %w", err)+ sourceNames, ok := runtimeSetNames(sourceDirectory, binaryName, variant)+ if !ok {+ return fmt.Errorf("source release does not contain a complete runtime set")+ }+ if verifier != nil {+ if err := verifier(filepath.Join(sourceDirectory, binaryName)); err != nil {+ return fmt.Errorf("source runtime binary failed verification: %w", err)+ }+ }+ if err := os.MkdirAll(destinationDirectory, 0755); err != nil {+ return err+ }+ if err := requireSafeRuntimeDirectory(destinationDirectory); err != nil {+ return err}- lock, err := acquireWindowsPairLock(dstDir)+ lock, err := acquireRuntimeSetLock(destinationDirectory)if err != nil {return err}defer func() {- if releaseErr := releaseWindowsPairLock(lock); result == nil && releaseErr != nil {- result = releaseErr- }+ attachRuntimeLockReleaseError(&result, releaseRuntimeSetLock(lock))}()-- // A contender may have committed while this process waited. Preserve that- // complete pair regardless of whether its authenticated release variant is- // byte-identical to this contender.- if windowsPairReady(dstDir, verifier) {- return nil+ if err := refreshRuntimeSetLock(lock); err != nil {+ return err}-- transaction, err := windowsPairToken()- if err != nil {+ if err := reconcileRuntimeBackups(+ destinationDirectory, binaryName, variant, verifier, lock,+ ); err != nil {return err}- staged := make(map[string]string, len(names))- stagedDigests := make(map[string][sha256.Size]byte, len(names))- backups := make(map[string]string, len(names))- publishedDigests := make(map[string][sha256.Size]byte, len(names))+ // A contender may have committed while this process waited. Its complete+ // runtime set wins and is never retired or mixed with this contender.+ if runtimeSetReady(destinationDirectory, binaryName, variant, verifier) {+ return nil+ }++ staged := make(map[string]string, len(sourceNames))+ backupDirectory := ""defer func() {for _, stagedPath := range staged {_ = os.Remove(stagedPath)@@ -838,23 +2023,49 @@ func installWindowsPairAtomicallyWithVerifier(}()operationErr := func() error {- for _, name := range names {- stagePath := filepath.Join(- dstDir, ".cbm-pair-stage-"+transaction+"-"+name)- if err := copyWindowsPairStage(- filepath.Join(srcDir, name), stagePath); err != nil {- return err- }- staged[name] = stagePath- digest, err := fileSHA256(stagePath)+ for _, name := range sourceNames {+ stagedPath, err := copyRuntimeStage(+ filepath.Join(sourceDirectory, name),+ destinationDirectory,+ name == binaryName,+ func() error { return refreshRuntimeSetLock(lock) },+ )if err != nil {return err}- stagedDigests[name] = digest+ staged[name] = stagedPath+ }+ if err := refreshRuntimeSetLock(lock); err != nil {+ return err+ }+ var err error+ backupDirectory, err = createRuntimeBackupDirectory(destinationDirectory)+ if err != nil {+ return err}- for _, name := range names {- target := filepath.Join(dstDir, name)+ entries, err := os.ReadDir(destinationDirectory)+ if err != nil {+ return err+ }+ retireNames := []string{binaryName, integrationsFileName}+ for _, entry := range entries {+ name := entry.Name()+ if strings.HasPrefix(name, "cbm-ui-") && strings.HasSuffix(name, ".pack") {+ retireNames = append(retireNames, name)+ }+ }+ retired := make(map[string]struct{}, len(retireNames))+ // Retire the executable first so a partial publication is never ready.+ for _, name := range retireNames {+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err+ }+ if _, duplicate := retired[name]; duplicate {+ continue+ }+ retired[name] = struct{}{}+ target := filepath.Join(destinationDirectory, name)status, err := os.Lstat(target)if os.IsNotExist(err) {continue@@ -862,65 +2073,102 @@ func installWindowsPairAtomicallyWithVerifier(if err != nil {return err}- if !status.Mode().IsRegular() {- return fmt.Errorf(- "refusing unsafe Windows package-cache target: %s", target)+ if !status.Mode().IsRegular() ||+ !platformRuntimeSetFileLinkCountOne(target, status) {+ return fmt.Errorf("refusing unsafe package-cache target: %s", target)}- backup := filepath.Join(- dstDir, ".cbm-pair-backup-"+transaction+"-"+name)- if err := os.Rename(target, backup); err != nil {+ backup := filepath.Join(backupDirectory, name)+ if err := renameFile(target, backup); err != nil {+ return err+ }+ }+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err+ }+ if runtimeBackupCrashObserver != nil {+ if err := runtimeBackupCrashObserver(+ runtimeBackupBeforeMarkerEvent, backupDirectory,+ ); err != nil {return err}- backups[name] = backup+ }+ if err := createRuntimeBackupMarker(+ backupDirectory, runtimeBackupRetired,+ ); err != nil {+ return err}- // Payload is the readiness signal and is deliberately published last.- for _, name := range names {- target := filepath.Join(dstDir, name)- if err := os.Rename(staged[name], target); err != nil {+ // runtimeSetNames orders every sidecar before the binary readiness signal.+ for _, name := range sourceNames {+ if err := assertRuntimeSetLockOwner(lock); err != nil {return err}+ target := filepath.Join(destinationDirectory, name)+ if err := renameFile(staged[name], target); err != nil {+ identical, compareErr := filesEqualSHA256(staged[name], target)+ if compareErr != nil || !identical {+ return err+ }+ _ = os.Remove(staged[name])+ }delete(staged, name)- publishedDigests[name] = stagedDigests[name]}- if !windowsPairReady(dstDir, verifier) {- return fmt.Errorf("published Windows package-cache pair failed verification")+ if !runtimeSetReady(destinationDirectory, binaryName, variant, verifier) {+ return fmt.Errorf("published package-cache runtime set failed verification")+ }+ if err := assertRuntimeSetLockOwner(lock); err != nil {+ return err}return nil}()- if operationErr == nil || windowsPairReady(dstDir, verifier) {- for _, backup := range backups {- _ = os.Remove(backup)+ if operationErr != nil {+ if lockErr := assertRuntimeSetLockOwner(lock); lockErr != nil {+ return fmt.Errorf("publication failed and lock ownership changed: %v: %w", operationErr, lockErr)}- return nil}-- // Roll back only files whose digest proves this transaction published them.- for index := len(names) - 1; index >= 0; index-- {- name := names[index]- digest, ok := publishedDigests[name]- target := filepath.Join(dstDir, name)- if ok && pathMatchesSHA256(target, digest) {- _ = os.Remove(target)+ if operationErr == nil {+ backup, err := inspectRuntimeBackupDirectory(+ destinationDirectory, filepath.Base(backupDirectory), binaryName,+ )+ if err != nil {+ return err}- }- for _, name := range names {- backup, ok := backups[name]- if !ok {- continue+ if err := cleanupRuntimeBackup(backup, lock); err != nil {+ return err}- target := filepath.Join(dstDir, name)- if _, err := os.Lstat(target); os.IsNotExist(err) {- _ = os.Rename(backup, target)+ return nil+ }+ preserveWinner := runtimeSetReady(+ destinationDirectory, binaryName, variant, verifier,+ )+ if backupDirectory != "" {+ if recoveryErr := reconcileRuntimeBackups(+ destinationDirectory, binaryName, variant, verifier, lock,+ ); recoveryErr != nil {+ return fmt.Errorf(+ "%v; package-cache recovery failed: %w", operationErr, recoveryErr,+ )}}+ if preserveWinner {+ return nil+ }return operationErr}-func installWindowsPairAtomically(srcDir, dstDir string) error {- return installWindowsPairAtomicallyWithVerifier(- srcDir, dstDir, verifyCandidate)+func publishRuntimeSetWithRecovery(+ sourceDirectory, destinationDirectory, binaryName, variant string,+ verifier func(string) error,+) error {+ return publishRuntimeSetWithRecoveryAndRenamer(+ sourceDirectory,+ destinationDirectory,+ binaryName,+ variant,+ verifier,+ os.Rename,+ )}func execBinary(executable string, args []string) error {@@ -933,3 +2181,164 @@ func execBinary(executable string, args []string) error {}return syscall.Exec(executable, append([]string{executable}, args...), os.Environ())}++func createMutationRuntimeSnapshot(+ executable, variant string,+ verifier func(string) error,+ maintainLease func() error,+) (snapshotDirectory, snapshotExecutable string, result error) {+ sourceDirectory := filepath.Dir(executable)+ binaryName := filepath.Base(executable)+ names, ok := runtimeSetNames(sourceDirectory, binaryName, variant)+ if !ok {+ return "", "", fmt.Errorf(+ "cached runtime assets changed before mutation snapshot",+ )+ }++ snapshotDirectory, err := platformCreatePrivateMutationRuntimeDirectory()+ if err != nil {+ return "", "", err+ }+ createdDirectory := snapshotDirectory+ defer func() {+ if result != nil {+ _ = os.RemoveAll(createdDirectory)+ }+ }()+ if err := requireSafeRuntimeDirectory(snapshotDirectory); err != nil {+ return "", "", fmt.Errorf(+ "owner-private mutation runtime snapshot is unsafe: %w", err,+ )+ }++ for _, name := range names {+ sourcePath := filepath.Join(sourceDirectory, name)+ expectedDigest, err := fileSHA256(sourcePath)+ if err != nil {+ return "", "", err+ }+ stagedPath, err := copyRuntimeStage(+ sourcePath,+ snapshotDirectory,+ name == binaryName,+ maintainLease,+ )+ if err != nil {+ return "", "", err+ }+ stagedDigest, digestErr := fileSHA256(stagedPath)+ if digestErr != nil || stagedDigest != expectedDigest ||+ !pathMatchesSHA256(sourcePath, expectedDigest) {+ _ = os.Remove(stagedPath)+ return "", "", fmt.Errorf(+ "cached runtime asset changed while mutation snapshot was copied: %s",+ name,+ )+ }+ if err := os.Rename(+ stagedPath, filepath.Join(snapshotDirectory, name),+ ); err != nil {+ _ = os.Remove(stagedPath)+ return "", "", err+ }+ }++ snapshotExecutable = filepath.Join(snapshotDirectory, binaryName)+ if !runtimeSetReady(+ snapshotDirectory, binaryName, variant, verifier,+ ) {+ return "", "", fmt.Errorf(+ "private mutation runtime snapshot failed verification",+ )+ }+ return snapshotDirectory, snapshotExecutable, nil+}++func runMutationBinary(executable string, args []string) error {+ cmd := exec.Command(executable, args...)+ cmd.Env = mutationSnapshotEnvironment()+ cmd.Stdin = os.Stdin+ cmd.Stdout = os.Stdout+ cmd.Stderr = os.Stderr+ return cmd.Run()+}++func execBinaryWithRuntimeLockAndRunner(+ executable string,+ args []string,+ variant string,+ verifier func(string) error,+ runner func(string, []string) error,+) (result error) {+ if runner == nil {+ return fmt.Errorf("missing mutation runtime runner")+ }+ directory := filepath.Dir(executable)+ if target, ok := mutationTargetDirectory(args); ok &&+ pathsReferToSameDirectory(target, directory) {+ return fmt.Errorf(+ "refusing mutation target that overlaps the shared package cache: %s",+ target,+ )+ }+ if err := requireSafeRuntimeDirectory(directory); err != nil {+ return err+ }+ lock, err := acquireRuntimeSetLock(directory)+ if err != nil {+ return err+ }+ lockHeld := true+ defer func() {+ if lockHeld {+ attachRuntimeLockReleaseError(&result, releaseRuntimeSetLock(lock))+ }+ }()+ if err := refreshRuntimeSetLock(lock); err != nil {+ return err+ }+ if !runtimeSetReady(+ directory, filepath.Base(executable), variant, verifier,+ ) {+ return fmt.Errorf("cached runtime assets changed before mutation launch")+ }+ snapshotDirectory, snapshotExecutable, err := createMutationRuntimeSnapshot(+ executable,+ variant,+ verifier,+ func() error { return refreshRuntimeSetLock(lock) },+ )+ if err != nil {+ return err+ }+ defer func() {+ // A hard-killed wrapper can bypass this cleanup while its native child+ // still consumes adjacent snapshot assets. Do not scavenge such a+ // directory by PID or age, and never replace the native command result+ // merely because best-effort cleanup leaked an isolated private copy.+ if cleanupErr := runtimeMutationSnapshotCleanup(snapshotDirectory); cleanupErr != nil {+ fmt.Fprintf(+ os.Stderr,+ "codebase-memory-mcp: warning: private mutation snapshot cleanup failed: %v\n",+ cleanupErr,+ )+ }+ }()+ releaseErr := releaseRuntimeSetLock(lock)+ lockHeld = false+ if releaseErr != nil {+ return releaseErr+ }+ return runner(snapshotExecutable, args)+}++func execBinaryWithRuntimeLock(executable string, args []string) error {+ return execBinaryWithRuntimeLockAndRunner(+ executable,+ args,+ runtimeVariant(),+ verifyCandidate,+ runMutationBinary,+ )+}diff --git a/pkg/go/cmd/codebase-memory-mcp/main_test.go b/pkg/go/cmd/codebase-memory-mcp/main_test.goindex 083a92479..c362e8f65 100644--- a/pkg/go/cmd/codebase-memory-mcp/main_test.go+++ b/pkg/go/cmd/codebase-memory-mcp/main_test.go@@ -1,197 +1,2149 @@package mainimport (+ "archive/tar"+ "archive/zip"+ "bytes"+ "compress/gzip"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors""fmt"+ "io"+ "net/http""os"+ "os/exec""path/filepath"+ "reflect"+ "runtime"+ "strconv""strings""sync""testing"+ "time")-func TestExecutionPathForOSUsesAdjacentWindowsLauncher(t *testing.T) {- payload := filepath.Join("cache", version, windowsPayloadName)- want := filepath.Join("cache", version, windowsLauncherName)+type archiveTestRoundTripper func(*http.Request) (*http.Response, error)- if got := executionPathForOS(payload, "windows"); got != want {- t.Fatalf("Windows execution path = %q, want adjacent launcher %q", got, want)+func (transport archiveTestRoundTripper) RoundTrip(+ request *http.Request,+) (*http.Response, error) {+ return transport(request)+}++type archiveCountingBody struct {+ reader io.Reader+ read int64+}++func (body *archiveCountingBody) Read(buffer []byte) (int, error) {+ count, err := body.reader.Read(buffer)+ body.read += int64(count)+ return count, err+}++func (*archiveCountingBody) Close() error { return nil }++func TestStandardAndUICachePathsDoNotCollide(t *testing.T) {+ t.Setenv("CBM_CACHE_DIR", t.TempDir())+ t.Setenv("CBM_VARIANT", "standard")+ standard := binPath()+ t.Setenv("CBM_VARIANT", "ui")+ ui := binPath()+ if standard == ui {+ t.Fatalf("standard and UI cache paths collide at %q", standard)+ }+ if filepath.Base(filepath.Dir(standard)) != "standard" ||+ filepath.Base(filepath.Dir(ui)) != "ui" {+ t.Fatalf("variant cache paths = %q and %q", standard, ui)}- if got := executionPathForOS(payload, "linux"); got != payload {- t.Fatalf("non-Windows execution path = %q, want payload %q", got, payload)+}++func TestWindowsUsesOneDirectBinary(t *testing.T) {+ binary := filepath.Join("cache", version, "ui", windowsBinaryName)+ if got := executionPathForOS(binary, "windows"); got != binary {+ t.Fatalf("Windows execution path = %q, want direct binary %q", got, binary)+ }+ if got := binaryNameForOS("windows"); got != "codebase-memory-mcp.exe" {+ t.Fatalf("Windows binary name = %q", got)+ }+ source, err := os.ReadFile("main.go")+ if err != nil {+ t.Fatal(err)+ }+ for _, obsolete := range []string{"payload", "launcher"} {+ if strings.Contains(strings.ToLower(string(source)), obsolete) {+ t.Fatalf("Go wrapper still contains obsolete %q model", obsolete)+ }}}-func TestPortableMutationActionPreservesPackageManagerRefusal(t *testing.T) {+func TestCacheSensitiveMutationActionIsExplicit(t *testing.T) {cases := []struct {args []stringwant string}{{args: []string{"update", "--yes"}, want: "update"},{args: []string{"uninstall", "--yes"}, want: "uninstall"},- {args: []string{"install", "--yes"}, want: ""},+ {args: []string{"install", "--yes"}, want: "install"},{args: []string{"cli", "update"}, want: ""},+ {args: []string{"daemon", "update"}, want: ""},}-for _, testCase := range cases {- if got := portableMutationAction(testCase.args); got != testCase.want {- t.Errorf("portableMutationAction(%q) = %q, want %q", testCase.args, got, testCase.want)+ if got := runtimeMutationAction(testCase.args); got != testCase.want {+ t.Errorf(+ "runtimeMutationAction(%q) = %q, want %q",+ testCase.args,+ got,+ testCase.want,+ )+ }+ }+}++func TestWrapperUninstallNeverDefaultsToItsCacheBinary(t *testing.T) {+ custom := []string{"uninstall", "--dir", filepath.Join("custom", "bin")}+ if got := nativeArgs(custom); !reflect.DeepEqual(got, custom) {+ t.Fatalf("custom uninstall args = %q, want %q", got, custom)+ }+ got := nativeArgs([]string{"uninstall", "--yes"})+ wantBase := "bin"+ if runtime.GOOS == "windows" {+ wantBase = "codebase-memory-mcp"+ }+ if len(got) != 4 || got[2] != "--dir" ||+ filepath.Base(got[3]) != wantBase {+ t.Fatalf("default uninstall args do not target managed install: %q", got)+ }+}++func TestArchiveNamespaceIsExactAndUIHasOnePack(t *testing.T) {+ binary := "codebase-memory-mcp"+ base := archiveNamesForOS("linux", binary)+ pack := "cbm-ui-" + strings.Repeat("a", 64) + ".pack"+ uiNames := append(append([]string(nil), base...), pack)+ got, err := validateArchiveMemberNames(uiNames, base, "ui", false)+ if err != nil {+ t.Fatal(err)+ }+ if got != pack {+ t.Fatalf("UI pack = %q, want %q", got, pack)+ }+ badCases := [][]string{+ append(append([]string(nil), uiNames...), "unexpected-root-file"),+ append(append([]string(nil), uiNames...),+ "cbm-ui-"+strings.Repeat("b", 64)+".pack"),+ base,+ }+ for _, names := range badCases {+ if _, err := validateArchiveMemberNames(names, base, "ui", false); err == nil {+ t.Fatalf("UI archive namespace accepted invalid members: %q", names)}}+ if _, err := validateArchiveMemberNames(uiNames, base, "standard", false); err == nil {+ t.Fatal("standard archive accepted a UI pack")+ }}-func writeTestWindowsPair(t *testing.T, directory, tag string) {+func writeTarGz(t *testing.T, archivePath string, names []string) {t.Helper()- if err := os.MkdirAll(directory, 0755); err != nil {+ file, err := os.Create(archivePath)+ if err != nil {t.Fatal(err)}- if err := os.WriteFile(- filepath.Join(directory, windowsLauncherName),- []byte("launcher:"+tag), 0755); err != nil {+ gz := gzip.NewWriter(file)+ tw := tar.NewWriter(gz)+ for _, name := range names {+ contents := []byte("contents:" + name)+ header := &tar.Header{+ Name: name,+ Mode: 0600,+ Size: int64(len(contents)),+ Typeflag: tar.TypeReg,+ }+ if err := tw.WriteHeader(header); err != nil {+ t.Fatal(err)+ }+ if _, err := tw.Write(contents); err != nil {+ t.Fatal(err)+ }+ }+ if err := tw.Close(); err != nil {t.Fatal(err)}- if err := os.WriteFile(- filepath.Join(directory, windowsPayloadName),- []byte("payload:"+tag), 0755); err != nil {+ if err := gz.Close(); err != nil {+ t.Fatal(err)+ }+ if err := file.Close(); err != nil {t.Fatal(err)}}-func verifyTestWindowsPair(launcherPath string) error {- launcher, err := os.ReadFile(launcherPath)+func TestTarExtractionValidatesNamespaceAndExtractsRuntimeSet(t *testing.T) {+ root := t.TempDir()+ archivePath := filepath.Join(root, "release.tar.gz")+ destination := filepath.Join(root, "extract")+ if err := os.Mkdir(destination, 0755); err != nil {+ t.Fatal(err)+ }+ binary := "codebase-memory-mcp"+ archiveNames := archiveNamesForOS("linux", binary)+ writeTarGz(t, archivePath, archiveNames)+ runtimeNames, err := extractTarGz(+ archivePath,+ destination,+ archiveNames,+ []string{binary, integrationsFileName},+ "standard",+ )if err != nil {- return err+ t.Fatal(err)+ }+ want := []string{binary, integrationsFileName}+ if !reflect.DeepEqual(runtimeNames, want) {+ t.Fatalf("extracted runtime names = %q, want %q", runtimeNames, want)+ }+ if _, err := os.Stat(filepath.Join(destination, "LICENSE")); !os.IsNotExist(err) {+ t.Fatal("non-runtime LICENSE member was extracted")+ }++ badArchive := filepath.Join(root, "bad.tar.gz")+ writeTarGz(t, badArchive, append(archiveNames, "unexpected-root-file"))+ badDestination := filepath.Join(root, "bad-extract")+ if err := os.Mkdir(badDestination, 0755); err != nil {+ t.Fatal(err)}- payload, err := os.ReadFile(- filepath.Join(filepath.Dir(launcherPath), windowsPayloadName))+ if _, err := extractTarGz(+ badArchive,+ badDestination,+ archiveNames,+ []string{binary, integrationsFileName},+ "standard",+ ); err == nil {+ t.Fatal("tar extraction accepted an unexpected root member")+ }+}++func TestTarExtractionRejectsHardlinkMember(t *testing.T) {+ root := t.TempDir()+ archivePath := filepath.Join(root, "hardlink.tar.gz")+ file, err := os.Create(archivePath)if err != nil {- return err+ t.Fatal(err)}- const prefix = "launcher:"- if !strings.HasPrefix(string(launcher), prefix) {- return fmt.Errorf("invalid launcher test fixture")+ gz := gzip.NewWriter(file)+ tw := tar.NewWriter(gz)+ if err := tw.WriteHeader(&tar.Header{+ Name: "codebase-memory-mcp", Typeflag: tar.TypeLink,+ Linkname: "cbm-integrations.json", Mode: 0755,+ }); err != nil {+ t.Fatal(err)}- tag := strings.TrimPrefix(string(launcher), prefix)- if string(payload) != "payload:"+tag {- return fmt.Errorf("launcher/payload test fixture mismatch")+ if err := tw.Close(); err != nil {+ t.Fatal(err)+ }+ if err := gz.Close(); err != nil {+ t.Fatal(err)+ }+ if err := file.Close(); err != nil {+ t.Fatal(err)+ }+ if _, err := tarGzMemberNames(archivePath); err == nil {+ t.Fatal("tar namespace accepted a hardlink member")+ }+}++func TestCompressedArchiveDownloadRejectsDeclaredAndActualOverflow(t *testing.T) {+ const maxBytes = int64(8)+ priorClient := httpsOnlyClient+ defer func() { httpsOnlyClient = priorClient }()++ t.Run("declared", func(t *testing.T) {+ httpsOnlyClient = &http.Client{Transport: archiveTestRoundTripper(+ func(request *http.Request) (*http.Response, error) {+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader("")),+ ContentLength: maxBytes + 1,+ Header: make(http.Header),+ Request: request,+ }, nil+ },+ )}+ destination := filepath.Join(t.TempDir(), "release.tar.gz")+ err := httpGetWithLimit(+ "https://example.invalid/release.tar.gz", destination, maxBytes,+ )+ if err == nil || !strings.Contains(err.Error(), "compressed safety limit") {+ t.Fatalf("compressed declared overflow error = %v", err)+ }+ if _, statErr := os.Stat(destination); !os.IsNotExist(statErr) {+ t.Fatal("declared oversized archive created a download")+ }+ })++ t.Run("actual", func(t *testing.T) {+ body := &archiveCountingBody{reader: bytes.NewReader(+ bytes.Repeat([]byte("x"), 1024),+ )}+ httpsOnlyClient = &http.Client{Transport: archiveTestRoundTripper(+ func(request *http.Request) (*http.Response, error) {+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: body,+ ContentLength: -1,+ Header: make(http.Header),+ Request: request,+ }, nil+ },+ )}+ destination := filepath.Join(t.TempDir(), "release.tar.gz")+ err := httpGetWithLimit(+ "https://example.invalid/release.tar.gz", destination, maxBytes,+ )+ if err == nil || !strings.Contains(err.Error(), "compressed safety limit") {+ t.Fatalf("compressed actual overflow error = %v", err)+ }+ if body.read != maxBytes+1 {+ t.Fatalf("oversized response bytes consumed = %d, want %d", body.read, maxBytes+1)+ }+ if _, statErr := os.Stat(destination); !os.IsNotExist(statErr) {+ t.Fatal("rejected compressed archive left a partial download")+ }+ })+}++func testArchiveLimits(+ members int, memberBytes, expandedBytes int64,+) archiveResourceLimits {+ return archiveResourceLimits{+ compressedBytes: 1024 * 1024,+ members: members,+ memberBytes: memberBytes,+ expandedBytes: expandedBytes,+ }+}++func TestTarArchiveRejectsMemberAndExpandedResourceOverflow(t *testing.T) {+ root := t.TempDir()+ tests := []struct {+ name string+ names []string+ limits archiveResourceLimits+ wantError string+ }{+ {+ name: "member count",+ names: []string{"one", "two", "three"},+ limits: testArchiveLimits(2, 1024, 4096),+ wantError: "member safety limit",+ },+ {+ name: "declared member bytes",+ names: []string{"oversized"},+ limits: testArchiveLimits(4, 4, 4096),+ wantError: "expanded safety limit",+ },+ {+ name: "declared aggregate bytes",+ names: []string{"one", "two"},+ limits: testArchiveLimits(4, 1024, 15),+ wantError: "aggregate expanded safety limit",+ },+ }+ for _, testCase := range tests {+ t.Run(testCase.name, func(t *testing.T) {+ archivePath := filepath.Join(root, strings.ReplaceAll(testCase.name, " ", "-")+".tar.gz")+ writeTarGz(t, archivePath, testCase.names)+ _, err := tarGzMemberNamesWithLimits(archivePath, testCase.limits)+ if err == nil || !strings.Contains(err.Error(), testCase.wantError) {+ t.Fatalf("tar resource overflow error = %v", err)+ }+ })+ }+}++func TestArchiveCopyRejectsActualMemberAggregateAndMetadataMismatch(t *testing.T) {+ tests := []struct {+ name string+ contents string+ declared int64+ actual int64+ limits archiveResourceLimits+ wantError string+ }{+ {+ name: "actual member bytes",+ contents: "12345",+ declared: 5,+ limits: testArchiveLimits(1, 4, 10),+ wantError: "actual expanded safety limit",+ },+ {+ name: "actual aggregate bytes",+ contents: "12",+ declared: 2,+ actual: 4,+ limits: testArchiveLimits(1, 10, 5),+ wantError: "aggregate actual expanded safety limit",+ },+ {+ name: "declared actual mismatch",+ contents: "123",+ declared: 2,+ limits: testArchiveLimits(1, 10, 10),+ wantError: "does not match declared size",+ },+ }+ for _, testCase := range tests {+ t.Run(testCase.name, func(t *testing.T) {+ actual := testCase.actual+ var output bytes.Buffer+ err := copyArchiveMemberWithLimits(+ &output,+ strings.NewReader(testCase.contents),+ "member",+ testCase.declared,+ &actual,+ testCase.limits,+ )+ if err == nil || !strings.Contains(err.Error(), testCase.wantError) {+ t.Fatalf("actual archive overflow error = %v", err)+ }+ })}- return nil}-func assertTestWindowsPair(t *testing.T, directory, tag string) {+func writeZip(t *testing.T, archivePath string, names []string) {t.Helper()- launcher, err := os.ReadFile(filepath.Join(directory, windowsLauncherName))+ file, err := os.Create(archivePath)if err != nil {t.Fatal(err)}- payload, err := os.ReadFile(filepath.Join(directory, windowsPayloadName))+ zw := zip.NewWriter(file)+ for _, name := range names {+ member, err := zw.Create(name)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := member.Write([]byte("contents:" + name)); err != nil {+ t.Fatal(err)+ }+ }+ if err := zw.Close(); err != nil {+ t.Fatal(err)+ }+ if err := file.Close(); err != nil {+ t.Fatal(err)+ }+}++func TestUIZipExtractionIncludesOneContentAddressedPack(t *testing.T) {+ root := t.TempDir()+ archivePath := filepath.Join(root, "release.zip")+ destination := filepath.Join(root, "extract")+ if err := os.Mkdir(destination, 0755); err != nil {+ t.Fatal(err)+ }+ pack := "cbm-ui-" + strings.Repeat("a", 64) + ".pack"+ archiveNames := archiveNamesForOS("windows", windowsBinaryName)+ writeZip(t, archivePath, append(archiveNames, pack))+ runtimeNames, err := extractZip(+ archivePath,+ destination,+ archiveNames,+ []string{windowsBinaryName, integrationsFileName},+ "ui",+ )if err != nil {t.Fatal(err)}- if string(launcher) != "launcher:"+tag || string(payload) != "payload:"+tag {- t.Fatalf("pair = %q / %q, want coherent tag %q", launcher, payload, tag)+ want := []string{windowsBinaryName, integrationsFileName, pack}+ if !reflect.DeepEqual(runtimeNames, want) {+ t.Fatalf("extracted runtime names = %q, want %q", runtimeNames, want)+ }+ for _, name := range want {+ if !regularRuntimeFile(filepath.Join(destination, name)) {+ t.Fatalf("runtime member %q was not extracted", name)+ }}}-func TestWindowsPairPublicationRepairsCorruptAndPartialCaches(t *testing.T) {+func TestZipArchiveRejectsMemberAndExpandedResourceOverflow(t *testing.T) {+ root := t.TempDir()tests := []struct {- name string- setup func(t *testing.T, destination string)+ name string+ names []string+ limits archiveResourceLimits+ wantError string}{{- name: "corrupt launcher",- setup: func(t *testing.T, destination string) {- writeTestWindowsPair(t, destination, "old")- if err := os.WriteFile(- filepath.Join(destination, windowsLauncherName),- []byte("corrupt"), 0755); err != nil {- t.Fatal(err)- }- },+ name: "member count",+ names: []string{"one", "two", "three"},+ limits: testArchiveLimits(2, 1024, 4096),+ wantError: "member safety limit",},{- name: "corrupt payload",- setup: func(t *testing.T, destination string) {- writeTestWindowsPair(t, destination, "old")- if err := os.WriteFile(- filepath.Join(destination, windowsPayloadName),- []byte("corrupt"), 0755); err != nil {- t.Fatal(err)- }- },+ name: "declared member bytes",+ names: []string{"oversized"},+ limits: testArchiveLimits(4, 4, 4096),+ wantError: "expanded safety limit",},{- name: "launcher only",- setup: func(t *testing.T, destination string) {- if err := os.MkdirAll(destination, 0755); err != nil {- t.Fatal(err)- }- if err := os.WriteFile(- filepath.Join(destination, windowsLauncherName),- []byte("launcher:partial"), 0755); err != nil {- t.Fatal(err)- }- },+ name: "declared aggregate bytes",+ names: []string{"one", "two"},+ limits: testArchiveLimits(4, 1024, 15),+ wantError: "aggregate expanded safety limit",},}-for _, testCase := range tests {t.Run(testCase.name, func(t *testing.T) {- root := t.TempDir()- source := filepath.Join(root, "source")- destination := filepath.Join(root, "destination")- writeTestWindowsPair(t, source, "candidate")- testCase.setup(t, destination)-- if err := installWindowsPairAtomicallyWithVerifier(- source, destination, verifyTestWindowsPair); err != nil {+ archivePath := filepath.Join(root, strings.ReplaceAll(testCase.name, " ", "-")+".zip")+ writeZip(t, archivePath, testCase.names)+ destination := filepath.Join(root, strings.ReplaceAll(testCase.name, " ", "-")+"-extract")+ if err := os.Mkdir(destination, 0755); err != nil {t.Fatal(err)}- assertTestWindowsPair(t, destination, "candidate")+ _, err := extractZipWithLimits(+ archivePath,+ destination,+ testCase.names,+ testCase.names[:1],+ "standard",+ testCase.limits,+ )+ if err == nil || !strings.Contains(err.Error(), testCase.wantError) {+ t.Fatalf("zip resource overflow error = %v", err)+ }})}}-func TestWindowsPairPublicationSerializesConcurrentCandidates(t *testing.T) {- root := t.TempDir()- destination := filepath.Join(root, "destination")- if err := os.MkdirAll(destination, 0755); err != nil {- t.Fatal(err)- }- sources := []string{filepath.Join(root, "source-a"), filepath.Join(root, "source-b")}- writeTestWindowsPair(t, sources[0], "a")- writeTestWindowsPair(t, sources[1], "b")-- start := make(chan struct{})- errors := make(chan error, len(sources))- var wait sync.WaitGroup- for _, source := range sources {- wait.Add(1)- go func(candidate string) {- defer wait.Done()- <-start- errors <- installWindowsPairAtomicallyWithVerifier(- candidate, destination, verifyTestWindowsPair)- }(source)- }- close(start)- wait.Wait()- close(errors)- for err := range errors {+func writeTestRuntimeSet(+ t *testing.T,+ directory, binaryName, tag, variant string,+) string {+ t.Helper()+ if err := os.MkdirAll(directory, 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(+ filepath.Join(directory, binaryName), []byte("binary:"+tag), 0755,+ ); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(+ filepath.Join(directory, integrationsFileName),+ []byte("integrations:"+tag),+ 0644,+ ); err != nil {+ t.Fatal(err)+ }+ pack := ""+ if variant == "ui" {+ packContents := []byte("pack:" + tag)+ digest := sha256.Sum256(packContents)+ pack = "cbm-ui-" + hex.EncodeToString(digest[:]) + ".pack"+ if err := os.WriteFile(+ filepath.Join(directory, pack), packContents, 0644,+ ); err != nil {+ t.Fatal(err)+ }+ }+ return pack+}++func verifyTestBinary(path string) error {+ contents, err := os.ReadFile(path)+ if err != nil {+ return err+ }+ if !strings.HasPrefix(string(contents), "binary:") {+ return fmt.Errorf("invalid test binary")+ }+ return nil+}++func TestRuntimeReadinessRequiresTheCompleteSelectedVariant(t *testing.T) {+ binary := "codebase-memory-mcp"+ standard := filepath.Join(t.TempDir(), "standard")+ writeTestRuntimeSet(t, standard, binary, "standard", "standard")+ if !runtimeSetReady(standard, binary, "standard", verifyTestBinary) {+ t.Fatal("complete standard runtime set is not ready")+ }+ if err := os.Remove(filepath.Join(standard, integrationsFileName)); err != nil {+ t.Fatal(err)+ }+ if runtimeSetReady(standard, binary, "standard", verifyTestBinary) {+ t.Fatal("runtime set without integrations sidecar is ready")+ }++ ui := filepath.Join(t.TempDir(), "ui")+ writeTestRuntimeSet(t, ui, binary, "ui", "ui")+ if !runtimeSetReady(ui, binary, "ui", verifyTestBinary) {+ t.Fatal("complete UI runtime set is not ready")+ }+ uiNames, ok := runtimeSetNames(ui, binary, "ui")+ if !ok {+ t.Fatal("complete UI runtime set has no member list")+ }+ pack := uiNames[1]+ if err := os.WriteFile(filepath.Join(ui, pack), []byte("corrupt"), 0644); err != nil {+ t.Fatal(err)+ }+ if runtimeSetReady(ui, binary, "ui", verifyTestBinary) {+ t.Fatal("UI runtime set accepts pack bytes that do not match the filename digest")+ }+ writeTestRuntimeSet(t, ui, binary, "ui", "ui")+ secondPack := "cbm-ui-" + strings.Repeat("b", 64) + ".pack"+ if err := os.WriteFile(filepath.Join(ui, secondPack), []byte("extra"), 0644); err != nil {+ t.Fatal(err)+ }+ if runtimeSetReady(ui, binary, "ui", verifyTestBinary) {+ t.Fatal("UI runtime set with two packs is ready")+ }+}++func assertRuntimeTag(+ t *testing.T,+ directory, binaryName, tag, variant string,+) {+ t.Helper()+ checks := map[string]string{+ binaryName: "binary:" + tag,+ integrationsFileName: "integrations:" + tag,+ }+ if variant == "ui" {+ packContents := []byte("pack:" + tag)+ digest := sha256.Sum256(packContents)+ checks["cbm-ui-"+hex.EncodeToString(digest[:])+".pack"] = "pack:" + tag+ }+ for name, want := range checks {+ contents, err := os.ReadFile(filepath.Join(directory, name))if err != nil {t.Fatal(err)}+ if string(contents) != want {+ t.Fatalf("%s = %q, want %q", name, contents, want)+ }}- if err := verifyTestWindowsPair(- filepath.Join(destination, windowsLauncherName)); err != nil {+}++func TestRuntimePublicationRepairsPartialCache(t *testing.T) {+ root := t.TempDir()+ source := filepath.Join(root, "source")+ destination := filepath.Join(root, "destination")+ binary := "codebase-memory-mcp"+ writeTestRuntimeSet(t, source, binary, "candidate", "ui")+ if err := os.Mkdir(destination, 0755); err != nil {t.Fatal(err)}- launcher, err := os.ReadFile(filepath.Join(destination, windowsLauncherName))- if err != nil {+ if err := os.WriteFile(+ filepath.Join(destination, binary), []byte("corrupt"), 0755,+ ); err != nil {+ t.Fatal(err)+ }+ stalePack := "cbm-ui-" + strings.Repeat("b", 64) + ".pack"+ if err := os.WriteFile(+ filepath.Join(destination, stalePack), []byte("stale"), 0644,+ ); err != nil {+ t.Fatal(err)+ }++ if err := publishRuntimeSetWithRecovery(+ source, destination, binary, "ui", verifyTestBinary,+ ); err != nil {+ t.Fatal(err)+ }+ assertRuntimeTag(t, destination, binary, "candidate", "ui")+ if _, err := os.Stat(filepath.Join(destination, stalePack)); !os.IsNotExist(err) {+ t.Fatal("stale UI pack survived runtime publication")+ }+}++func TestRuntimePublicationRepairsDigestMismatchedPack(t *testing.T) {+ root := t.TempDir()+ source := filepath.Join(root, "source")+ destination := filepath.Join(root, "destination")+ binary := "codebase-memory-mcp"+ writeTestRuntimeSet(t, source, binary, "candidate", "ui")+ oldPack := writeTestRuntimeSet(t, destination, binary, "old", "ui")+ if err := os.WriteFile(+ filepath.Join(destination, oldPack), []byte("corrupt pack"), 0644,+ ); err != nil {+ t.Fatal(err)+ }+ if runtimeSetReady(destination, binary, "ui", verifyTestBinary) {+ t.Fatal("digest-mismatched destination pack was accepted before repair")+ }++ if err := publishRuntimeSetWithRecovery(+ source, destination, binary, "ui", verifyTestBinary,+ ); err != nil {+ t.Fatal(err)+ }+ assertRuntimeTag(t, destination, binary, "candidate", "ui")+ if _, err := os.Stat(filepath.Join(destination, oldPack)); !os.IsNotExist(err) {+ t.Fatal("digest-mismatched UI pack survived runtime publication")+ }+}++func TestRuntimePublicationCommitsSidecarsBeforeBinary(t *testing.T) {+ root := t.TempDir()+ source := filepath.Join(root, "source")+ destination := filepath.Join(root, "destination")+ binary := "codebase-memory-mcp"+ pack := writeTestRuntimeSet(t, source, binary, "candidate", "ui")+ committed := []string{}+ renameFile := func(sourcePath, destinationPath string) error {+ name := filepath.Base(destinationPath)+ if filepath.Dir(destinationPath) == destination &&+ (name == binary || name == integrationsFileName || name == pack) {+ committed = append(committed, name)+ }+ return os.Rename(sourcePath, destinationPath)+ }+ if err := publishRuntimeSetWithRecoveryAndRenamer(+ source,+ destination,+ binary,+ "ui",+ verifyTestBinary,+ renameFile,+ ); err != nil {+ t.Fatal(err)+ }+ want := []string{integrationsFileName, pack, binary}+ if !reflect.DeepEqual(committed, want) {+ t.Fatalf("runtime commit order = %q, want %q", committed, want)+ }+}++func TestRuntimePublicationCrashHelper(t *testing.T) {+ if os.Getenv("CBM_TEST_RUNTIME_CRASH_HELPER") != "1" {+ return+ }+ source := os.Getenv("CBM_TEST_RUNTIME_CRASH_SOURCE")+ destination := os.Getenv("CBM_TEST_RUNTIME_CRASH_DESTINATION")+ marker := os.Getenv("CBM_TEST_RUNTIME_CRASH_MARKER")+ crashPhase := os.Getenv("CBM_TEST_RUNTIME_CRASH_PHASE")+ binary := "codebase-memory-mcp"+ reachCrashGate := func() error {+ if err := os.WriteFile(marker, []byte("reached\n"), 0600); err != nil {+ return err+ }+ for {+ time.Sleep(time.Hour)+ }+ }+ priorCrashObserver := runtimeBackupCrashObserver+ defer func() { runtimeBackupCrashObserver = priorCrashObserver }()+ runtimeBackupCrashObserver = func(event, _ string) error {+ if event == crashPhase {+ return reachCrashGate()+ }+ return nil+ }+ renameFile := func(sourcePath, destinationPath string) error {+ if err := os.Rename(sourcePath, destinationPath); err != nil {+ return err+ }+ backupParent := filepath.Base(filepath.Dir(destinationPath))+ if crashPhase == "retired-executable" &&+ runtimeBackupDirectoryName(backupParent) &&+ filepath.Base(destinationPath) == binary {+ return reachCrashGate()+ }+ if crashPhase == "published-integrations" &&+ destinationPath == filepath.Join(destination, integrationsFileName) {+ return reachCrashGate()+ }+ if crashPhase == "published-binary" &&+ destinationPath == filepath.Join(destination, binary) {+ return reachCrashGate()+ }+ return nil+ }+ if err := publishRuntimeSetWithRecoveryAndRenamer(+ source,+ destination,+ binary,+ "standard",+ verifyTestBinary,+ renameFile,+ ); err != nil {t.Fatal(err)}- tag := strings.TrimPrefix(string(launcher), "launcher:")- if tag != "a" && tag != "b" {- t.Fatalf("unexpected concurrent winner tag %q", tag)+}++func TestKilledRuntimePublisherIsReconciledByLockedReadiness(t *testing.T) {+ for _, testCase := range []struct {+ name string+ crashPhase string+ expectedReady bool+ expectedBackupMembers int+ expectRetiredMarker bool+ expectCleanupMarker bool+ }{+ {+ name: "executable retired before other leaves",+ crashPhase: "retired-executable",+ expectedReady: false,+ expectedBackupMembers: 1,+ },+ {+ name: "all leaves retired before retirement marker",+ crashPhase: runtimeBackupBeforeMarkerEvent,+ expectedReady: false,+ expectedBackupMembers: 2,+ },+ {+ name: "partial sidecar publish",+ crashPhase: "published-integrations",+ expectedReady: false,+ expectedBackupMembers: 2,+ expectRetiredMarker: true,+ },+ {+ name: "complete publish before cleanup",+ crashPhase: "published-binary",+ expectedReady: true,+ expectedBackupMembers: 2,+ expectRetiredMarker: true,+ },+ {+ name: "cleanup interrupted after one retired member",+ crashPhase: runtimeBackupCleanupRemovedEvent,+ expectedReady: true,+ expectedBackupMembers: 1,+ expectRetiredMarker: true,+ expectCleanupMarker: true,+ },+ } {+ t.Run(testCase.name, func(t *testing.T) {+ root := t.TempDir()+ source := filepath.Join(root, "source")+ destination := filepath.Join(root, "destination")+ marker := filepath.Join(root, "crash-reached")+ binary := "codebase-memory-mcp"+ writeTestRuntimeSet(t, source, binary, "candidate", "standard")+ writeTestRuntimeSet(t, destination, binary, "old", "standard")+ if err := os.WriteFile(+ filepath.Join(destination, binary), []byte("corrupt:old"), 0755,+ ); err != nil {+ t.Fatal(err)+ }++ command := exec.Command(+ os.Args[0], "-test.run=^TestRuntimePublicationCrashHelper$",+ )+ command.Env = append(+ os.Environ(),+ "CBM_TEST_RUNTIME_CRASH_HELPER=1",+ "CBM_TEST_RUNTIME_CRASH_SOURCE="+source,+ "CBM_TEST_RUNTIME_CRASH_DESTINATION="+destination,+ "CBM_TEST_RUNTIME_CRASH_MARKER="+marker,+ "CBM_TEST_RUNTIME_CRASH_PHASE="+testCase.crashPhase,+ )+ var stderr bytes.Buffer+ command.Stderr = &stderr+ if err := command.Start(); err != nil {+ t.Fatal(err)+ }+ waitResult := make(chan error, 1)+ go func() { waitResult <- command.Wait() }()+ finished := false+ defer func() {+ if !finished {+ _ = command.Process.Kill()+ <-waitResult+ }+ }()++ deadline := time.Now().Add(10 * time.Second)+ for {+ if _, err := os.Stat(marker); err == nil {+ break+ }+ select {+ case err := <-waitResult:+ finished = true+ t.Fatalf(+ "publication helper exited before crash gate: %v: %s",+ err, stderr.String(),+ )+ default:+ }+ if time.Now().After(deadline) {+ t.Fatalf(+ "publication helper did not reach crash gate: %s",+ stderr.String(),+ )+ }+ time.Sleep(10 * time.Millisecond)+ }++ entries, err := os.ReadDir(destination)+ if err != nil {+ t.Fatal(err)+ }+ backupCount := 0+ for _, entry := range entries {+ if runtimeBackupDirectoryName(entry.Name()) {+ backupCount+++ if !entry.IsDir() {+ t.Fatal("killed publisher backup transaction is not a directory")+ }+ backupPath := filepath.Join(destination, entry.Name())+ backupEntries, err := os.ReadDir(backupPath)+ if err != nil {+ t.Fatal(err)+ }+ memberCount := 0+ for _, backupEntry := range backupEntries {+ if runtimeBackupTargetName(backupEntry.Name(), binary) {+ memberCount+++ }+ }+ if memberCount != testCase.expectedBackupMembers {+ t.Fatalf(+ "backup member count at crash gate = %d, want %d",+ memberCount, testCase.expectedBackupMembers,+ )+ }+ for markerName, expected := range map[string]bool{+ runtimeBackupRetired: testCase.expectRetiredMarker,+ runtimeBackupCleanupOnly: testCase.expectCleanupMarker,+ } {+ _, markerErr := os.Stat(filepath.Join(backupPath, markerName))+ if expected && markerErr != nil {+ t.Fatalf("expected backup marker %s is missing: %v", markerName, markerErr)+ }+ if !expected && !os.IsNotExist(markerErr) {+ t.Fatalf("unexpected backup marker %s exists", markerName)+ }+ }+ }+ }+ if backupCount != 1 {+ t.Fatalf("killed publisher backup count = %d, want 1", backupCount)+ }++ if err := command.Process.Kill(); err != nil {+ t.Fatal(err)+ }+ if err := <-waitResult; err == nil {+ t.Fatal("publication helper was not killed")+ }+ finished = true++ ready, err := runtimeSetReadyLocked(+ destination, binary, "standard", verifyTestBinary,+ )+ if err != nil {+ t.Fatal(err)+ }+ if ready != testCase.expectedReady {+ t.Fatalf(+ "reconciled readiness = %v, want %v",+ ready, testCase.expectedReady,+ )+ }+ if !ready {+ contents, err := os.ReadFile(filepath.Join(destination, binary))+ if err != nil {+ t.Fatal(err)+ }+ if string(contents) != "corrupt:old" {+ t.Fatalf("recovered prior binary = %q", contents)+ }+ contents, err = os.ReadFile(+ filepath.Join(destination, integrationsFileName),+ )+ if err != nil {+ t.Fatal(err)+ }+ if string(contents) != "integrations:old" {+ t.Fatalf("recovered prior integrations = %q", contents)+ }+ if err := publishRuntimeSetWithRecovery(+ source, destination, binary, "standard", verifyTestBinary,+ ); err != nil {+ t.Fatal(err)+ }+ }+ assertRuntimeTag(+ t, destination, binary, "candidate", "standard",+ )+ entries, err = os.ReadDir(destination)+ if err != nil {+ t.Fatal(err)+ }+ for _, entry := range entries {+ if strings.HasPrefix(entry.Name(), runtimeBackupPrefix) {+ t.Fatalf("orphan backup survived recovery: %s", entry.Name())+ }+ }+ if _, err := os.Stat(filepath.Join(+ destination, runtimeSetLockName,+ )); !os.IsNotExist(err) {+ t.Fatal("runtime-set lock survived killed-process recovery")+ }+ })+ }+}++func TestConcurrentRuntimePublishersAreSerialized(t *testing.T) {+ root := t.TempDir()+ firstSource := filepath.Join(root, "source-first")+ secondSource := filepath.Join(root, "source-second")+ destination := filepath.Join(root, "destination")+ binary := "codebase-memory-mcp"+ firstPack := writeTestRuntimeSet(+ t, firstSource, binary, "first", "ui",+ )+ secondPack := writeTestRuntimeSet(+ t, secondSource, binary, "second", "ui",+ )++ firstPaused := make(chan struct{})+ releaseFirst := make(chan struct{})+ secondWaiting := make(chan struct{})+ secondEnteredPublication := make(chan struct{})+ firstResult := make(chan error, 1)+ secondResult := make(chan error, 1)+ var pauseOnce sync.Once+ var waitOnce sync.Once+ var enteredOnce sync.Once+ priorObserver := runtimeSetLockWaitObserver+ runtimeSetLockWaitObserver = func() {+ waitOnce.Do(func() { close(secondWaiting) })+ }+ defer func() { runtimeSetLockWaitObserver = priorObserver }()++ firstRenamer := func(sourcePath, destinationPath string) error {+ if err := os.Rename(sourcePath, destinationPath); err != nil {+ return err+ }+ if destinationPath == filepath.Join(destination, integrationsFileName) {+ pauseOnce.Do(func() {+ close(firstPaused)+ <-releaseFirst+ })+ }+ return nil+ }+ secondRenamer := func(sourcePath, destinationPath string) error {+ name := filepath.Base(destinationPath)+ if filepath.Dir(destinationPath) == destination &&+ (name == binary || name == integrationsFileName || name == secondPack) {+ enteredOnce.Do(func() { close(secondEnteredPublication) })+ }+ return os.Rename(sourcePath, destinationPath)+ }++ go func() {+ firstResult <- publishRuntimeSetWithRecoveryAndRenamer(+ firstSource,+ destination,+ binary,+ "ui",+ verifyTestBinary,+ firstRenamer,+ )+ }()+ select {+ case <-firstPaused:+ case <-time.After(5 * time.Second):+ t.Fatal("first publisher did not reach the held publication gate")+ }++ go func() {+ secondResult <- publishRuntimeSetWithRecoveryAndRenamer(+ secondSource,+ destination,+ binary,+ "ui",+ verifyTestBinary,+ secondRenamer,+ )+ }()++ concurrentPublication := false+ var secondErr error+ select {+ case <-secondWaiting:+ // The serialized implementation reaches this branch while the first+ // publisher still owns the held publication gate.+ case <-secondEnteredPublication:+ concurrentPublication = true+ select {+ case secondErr = <-secondResult:+ case <-time.After(5 * time.Second):+ close(releaseFirst)+ t.Fatal("concurrent second publisher did not finish")+ }+ case <-time.After(5 * time.Second):+ close(releaseFirst)+ t.Fatal("second publisher neither waited nor entered publication")+ }+ close(releaseFirst)++ var firstErr error+ select {+ case firstErr = <-firstResult:+ case <-time.After(5 * time.Second):+ t.Fatal("first publisher did not finish after its gate was released")+ }+ if !concurrentPublication {+ select {+ case secondErr = <-secondResult:+ case <-time.After(5 * time.Second):+ t.Fatal("serialized second publisher did not finish")+ }+ }+ if concurrentPublication {+ t.Fatal("second publisher entered publication while the first sequence was held")+ }+ if firstErr != nil {+ t.Fatalf("first publisher failed: %v", firstErr)+ }+ if secondErr != nil {+ t.Fatalf("serialized second publisher failed: %v", secondErr)+ }+ assertRuntimeTag(t, destination, binary, "first", "ui")+ if _, err := os.Stat(filepath.Join(destination, secondPack)); !os.IsNotExist(err) {+ t.Fatal("serialized losing publisher damaged the winning runtime set")+ }+ if _, err := os.Stat(filepath.Join(destination, firstPack)); err != nil {+ t.Fatalf("winning UI pack is missing: %v", err)+ }+}++func TestConcurrentPublisherWaitsForRollbackBeforePublishing(t *testing.T) {+ root := t.TempDir()+ firstSource := filepath.Join(root, "source-first")+ secondSource := filepath.Join(root, "source-second")+ destination := filepath.Join(root, "destination")+ binary := "codebase-memory-mcp"+ firstPack := writeTestRuntimeSet(+ t, firstSource, binary, "first", "ui",+ )+ secondPack := writeTestRuntimeSet(+ t, secondSource, binary, "second", "ui",+ )+ oldPack := writeTestRuntimeSet(t, destination, binary, "old", "ui")+ verifier := func(path string) error {+ contents, err := os.ReadFile(path)+ if err != nil {+ return err+ }+ if string(contents) == "binary:old" {+ return fmt.Errorf("old runtime set requires repair")+ }+ return verifyTestBinary(path)+ }++ firstPaused := make(chan struct{})+ releaseFirst := make(chan struct{})+ secondWaiting := make(chan struct{})+ secondEnteredPublication := make(chan struct{})+ firstResult := make(chan error, 1)+ secondResult := make(chan error, 1)+ var pauseOnce sync.Once+ var waitOnce sync.Once+ var enteredOnce sync.Once+ priorObserver := runtimeSetLockWaitObserver+ runtimeSetLockWaitObserver = func() {+ waitOnce.Do(func() { close(secondWaiting) })+ }+ defer func() { runtimeSetLockWaitObserver = priorObserver }()++ failedBinary := false+ firstRenamer := func(sourcePath, destinationPath string) error {+ if destinationPath == filepath.Join(destination, binary) && !failedBinary {+ failedBinary = true+ return fmt.Errorf("injected binary publication failure")+ }+ if err := os.Rename(sourcePath, destinationPath); err != nil {+ return err+ }+ if destinationPath == filepath.Join(destination, integrationsFileName) {+ pauseOnce.Do(func() {+ close(firstPaused)+ <-releaseFirst+ })+ }+ return nil+ }+ secondRenamer := func(sourcePath, destinationPath string) error {+ name := filepath.Base(destinationPath)+ if filepath.Dir(destinationPath) == destination &&+ (name == binary || name == integrationsFileName || name == secondPack) {+ enteredOnce.Do(func() { close(secondEnteredPublication) })+ }+ return os.Rename(sourcePath, destinationPath)+ }++ go func() {+ firstResult <- publishRuntimeSetWithRecoveryAndRenamer(+ firstSource,+ destination,+ binary,+ "ui",+ verifier,+ firstRenamer,+ )+ }()+ select {+ case <-firstPaused:+ case <-time.After(5 * time.Second):+ t.Fatal("failing publisher did not reach the held publication gate")+ }++ go func() {+ secondResult <- publishRuntimeSetWithRecoveryAndRenamer(+ secondSource,+ destination,+ binary,+ "ui",+ verifier,+ secondRenamer,+ )+ }()++ concurrentPublication := false+ var secondErr error+ select {+ case <-secondWaiting:+ case <-secondEnteredPublication:+ concurrentPublication = true+ select {+ case secondErr = <-secondResult:+ case <-time.After(5 * time.Second):+ close(releaseFirst)+ t.Fatal("concurrent second publisher did not finish")+ }+ case <-time.After(5 * time.Second):+ close(releaseFirst)+ t.Fatal("second publisher neither waited nor entered failing publication")+ }+ close(releaseFirst)++ var firstErr error+ select {+ case firstErr = <-firstResult:+ case <-time.After(5 * time.Second):+ t.Fatal("failing publisher did not finish rollback")+ }+ if !concurrentPublication {+ select {+ case secondErr = <-secondResult:+ case <-time.After(5 * time.Second):+ t.Fatal("publisher waiting for rollback did not finish")+ }+ }+ if concurrentPublication {+ t.Fatal("second publisher entered publication before rollback completed")+ }+ if firstErr == nil || !failedBinary {+ t.Fatal("first publisher did not report the injected publication failure")+ }+ if secondErr != nil {+ t.Fatalf("publisher after rollback failed: %v", secondErr)+ }+ assertRuntimeTag(t, destination, binary, "second", "ui")+ for _, obsoletePack := range []string{firstPack, oldPack} {+ if _, err := os.Stat(filepath.Join(destination, obsoletePack)); !os.IsNotExist(err) {+ t.Fatalf("obsolete UI pack survived serialized rollback: %s", obsoletePack)+ }+ }+ if _, err := os.Stat(filepath.Join(destination, secondPack)); err != nil {+ t.Fatalf("post-rollback winner's UI pack is missing: %v", err)+ }+ if !runtimeSetReady(destination, binary, "ui", verifier) {+ t.Fatal("post-rollback winner is incomplete")+ }+}++func TestRuntimePublicationFailureRestoresPriorCompleteSet(t *testing.T) {+ root := t.TempDir()+ source := filepath.Join(root, "source")+ destination := filepath.Join(root, "destination")+ binary := "codebase-memory-mcp"+ candidatePack := writeTestRuntimeSet(+ t, source, binary, "candidate", "ui",+ )+ oldPack := writeTestRuntimeSet(t, destination, binary, "old", "ui")+ verifier := func(path string) error {+ contents, err := os.ReadFile(path)+ if err != nil {+ return err+ }+ if string(contents) == "binary:old" {+ return fmt.Errorf("old runtime set requires repair")+ }+ return verifyTestBinary(path)+ }+ failed := false+ renameFile := func(sourcePath, destinationPath string) error {+ if destinationPath == filepath.Join(destination, binary) && !failed {+ failed = true+ return fmt.Errorf("injected binary publication failure")+ }+ return os.Rename(sourcePath, destinationPath)+ }++ err := publishRuntimeSetWithRecoveryAndRenamer(+ source,+ destination,+ binary,+ "ui",+ verifier,+ renameFile,+ )+ if err == nil {+ t.Fatal("injected publication failure unexpectedly succeeded")+ }+ if !failed {+ t.Fatal("test did not reach the injected binary publication failure")+ }+ assertRuntimeTag(t, destination, binary, "old", "ui")+ if !runtimeSetReady(destination, binary, "ui", nil) {+ t.Fatal("rollback did not restore a structurally complete prior set")+ }+ if _, err := os.Stat(filepath.Join(destination, candidatePack)); !os.IsNotExist(err) {+ t.Fatal("failed candidate UI pack survived rollback")+ }+ if _, err := os.Stat(filepath.Join(destination, oldPack)); err != nil {+ t.Fatalf("rolled-back UI pack is missing: %v", err)+ }+ if _, err := os.Stat(filepath.Join(destination, runtimeSetLockName)); !os.IsNotExist(err) {+ t.Fatal("runtime-set lock survived rollback")+ }+}++func TestMutationSnapshotReleasesCacheLockAndCleansAfterLaunchFailure(t *testing.T) {+ directory := t.TempDir()+ binary := "codebase-memory-mcp"+ executable := filepath.Join(directory, binary)+ writeTestRuntimeSet(t, directory, binary, "cached", "standard")+ var snapshotExecutable string+ runnerCalled := false+ err := execBinaryWithRuntimeLockAndRunner(+ executable,+ []string{"install", "--yes"},+ "standard",+ verifyTestBinary,+ func(candidate string, args []string) error {+ runnerCalled = true+ snapshotExecutable = candidate+ if reflect.DeepEqual(args, []string{"install", "--yes"}) == false {+ t.Fatalf("snapshot mutation args = %q", args)+ }+ if filepath.Dir(candidate) == directory {+ t.Fatal("mutation launched from the shared package cache")+ }+ status, err := os.Lstat(filepath.Dir(candidate))+ if err != nil {+ t.Fatal(err)+ }+ if !status.IsDir() ||+ (runtime.GOOS != "windows" && status.Mode().Perm()&0077 != 0) {+ t.Fatalf("mutation snapshot mode = %v, want owner-private", status.Mode())+ }+ assertRuntimeTag(+ t, filepath.Dir(candidate), binary, "cached", "standard",+ )+ if _, err := os.Stat(filepath.Join(+ directory, runtimeSetLockName,+ )); !os.IsNotExist(err) {+ t.Fatal("cache lock remained held when snapshot runner started")+ }+ if err := os.WriteFile(+ executable, []byte("binary:successor"), 0755,+ ); err != nil {+ t.Fatal(err)+ }+ contents, err := os.ReadFile(candidate)+ if err != nil {+ t.Fatal(err)+ }+ if string(contents) != "binary:cached" {+ t.Fatalf("cache mutation changed private snapshot: %q", contents)+ }+ return fmt.Errorf("injected snapshot launch failure")+ },+ )+ if err == nil || !strings.Contains(err.Error(), "injected snapshot launch failure") {+ t.Fatalf("mutation launch failure = %v", err)+ }+ if !runnerCalled {+ t.Fatal("verified mutation snapshot was not launched")+ }+ if _, err := os.Stat(filepath.Dir(snapshotExecutable)); !os.IsNotExist(err) {+ t.Fatal("failed mutation left its private runtime snapshot")+ }+ if _, err := os.Stat(filepath.Join(+ directory, runtimeSetLockName,+ )); !os.IsNotExist(err) {+ t.Fatal("failed mutation left the package-cache lock")+ }+}++func TestMutationSnapshotEnvironmentIgnoresExternalAssetOverrides(t *testing.T) {+ t.Setenv("CBM_ASSETS_DIR", filepath.Join(t.TempDir(), "integrations"))+ t.Setenv("CBM_UI_ASSETS_DIR", filepath.Join(t.TempDir(), "ui"))+ for _, entry := range mutationSnapshotEnvironment() {+ name := entry+ if separator := strings.IndexByte(entry, '='); separator >= 0 {+ name = entry[:separator]+ }+ if strings.EqualFold(name, "CBM_ASSETS_DIR") ||+ strings.EqualFold(name, "CBM_UI_ASSETS_DIR") {+ t.Fatalf("mutation snapshot environment retained %q", entry)+ }+ }+}++func TestMutationSnapshotRejectsExplicitTargetOverlappingCache(t *testing.T) {+ directory := t.TempDir()+ executable := filepath.Join(directory, "codebase-memory-mcp")+ for _, args := range [][]string{+ {"install", "--dir", directory},+ {"uninstall", "--dir=" + directory},+ } {+ runnerCalled := false+ err := execBinaryWithRuntimeLockAndRunner(+ executable,+ args,+ "standard",+ nil,+ func(string, []string) error {+ runnerCalled = true+ return nil+ },+ )+ if err == nil || !strings.Contains(err.Error(), "overlaps the shared package cache") {+ t.Fatalf("overlapping mutation target error = %v", err)+ }+ if runnerCalled {+ t.Fatal("overlapping cache mutation target was launched")+ }+ }+}++func TestMutationSnapshotVerifierFailureNeverLaunches(t *testing.T) {+ directory := t.TempDir()+ binary := "codebase-memory-mcp"+ executable := filepath.Join(directory, binary)+ writeTestRuntimeSet(t, directory, binary, "cached", "standard")+ verifierCalls := 0+ verifier := func(path string) error {+ verifierCalls+++ if filepath.Dir(path) != directory {+ return fmt.Errorf("injected private snapshot verification failure")+ }+ return verifyTestBinary(path)+ }+ runnerCalled := false+ err := execBinaryWithRuntimeLockAndRunner(+ executable,+ []string{"install", "--yes"},+ "standard",+ verifier,+ func(string, []string) error {+ runnerCalled = true+ return nil+ },+ )+ if err == nil || !strings.Contains(err.Error(), "failed verification") {+ t.Fatalf("snapshot verifier failure = %v", err)+ }+ if verifierCalls != 2 {+ t.Fatalf("snapshot verifier calls = %d, want source and snapshot", verifierCalls)+ }+ if runnerCalled {+ t.Fatal("mutation runner was invoked after snapshot verification failure")+ }+ if _, err := os.Stat(filepath.Join(+ directory, runtimeSetLockName,+ )); !os.IsNotExist(err) {+ t.Fatal("snapshot verification failure left the package-cache lock")+ }+}++func TestMutationSnapshotPreservesCompleteUIRuntimeSet(t *testing.T) {+ directory := t.TempDir()+ binary := "codebase-memory-mcp"+ executable := filepath.Join(directory, binary)+ pack := writeTestRuntimeSet(t, directory, binary, "ui-cached", "ui")+ var snapshotDirectory string+ err := execBinaryWithRuntimeLockAndRunner(+ executable,+ []string{"install", "--yes"},+ "ui",+ verifyTestBinary,+ func(candidate string, _ []string) error {+ snapshotDirectory = filepath.Dir(candidate)+ names, ok := runtimeSetNames(snapshotDirectory, binary, "ui")+ want := []string{integrationsFileName, pack, binary}+ if !ok || !reflect.DeepEqual(names, want) {+ t.Fatalf("UI mutation snapshot names = %q, want %q", names, want)+ }+ assertRuntimeTag(+ t, snapshotDirectory, binary, "ui-cached", "ui",+ )+ return nil+ },+ )+ if err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(snapshotDirectory); !os.IsNotExist(err) {+ t.Fatal("successful UI mutation left its private runtime snapshot")+ }+}++func TestMutationSnapshotCleanupFailurePreservesNativeResult(t *testing.T) {+ const exitHelper = "CBM_GO_MUTATION_EXIT_HELPER"+ if os.Getenv(exitHelper) == "1" {+ os.Exit(7)+ }+ exitCommand := exec.Command(+ os.Args[0],+ "-test.run=^TestMutationSnapshotCleanupFailurePreservesNativeResult$",+ )+ exitCommand.Env = append(os.Environ(), exitHelper+"=1")+ nativeErr := exitCommand.Run()+ exitErr, ok := nativeErr.(*exec.ExitError)+ if !ok {+ t.Fatalf("exit helper error = %T %v", nativeErr, nativeErr)+ }++ priorCleanup := runtimeMutationSnapshotCleanup+ defer func() { runtimeMutationSnapshotCleanup = priorCleanup }()+ runtimeMutationSnapshotCleanup = func(path string) error {+ if err := os.RemoveAll(path); err != nil {+ return err+ }+ return errors.New("injected private snapshot cleanup failure")+ }+ for _, testCase := range []struct {+ name string+ runnerErr error+ wantResult error+ }{+ {name: "native success remains success"},+ {name: "native exit error identity survives", runnerErr: exitErr, wantResult: exitErr},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ directory := t.TempDir()+ binary := "codebase-memory-mcp"+ writeTestRuntimeSet(t, directory, binary, "cached", "standard")+ result := execBinaryWithRuntimeLockAndRunner(+ filepath.Join(directory, binary),+ []string{"install", "--yes"},+ "standard",+ verifyTestBinary,+ func(string, []string) error { return testCase.runnerErr },+ )+ if result != testCase.wantResult {+ t.Fatalf("native result identity changed: got %v, want %v", result, testCase.wantResult)+ }+ if exitErr != nil && testCase.wantResult != nil {+ var recovered *exec.ExitError+ if !errors.As(result, &recovered) || recovered != exitErr {+ t.Fatal("native ExitError was not preserved through cleanup failure")+ }+ }+ })+ }+}++func TestMutationSnapshotParentDeathLeavesCacheRecoverable(t *testing.T) {+ const roleEnvironment = "CBM_GO_MUTATION_SNAPSHOT_ROLE"+ role := os.Getenv(roleEnvironment)+ if role == "child" {+ executable, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ info := fmt.Sprintf("%d\n%s\n", os.Getpid(), executable)+ if err := os.WriteFile(+ os.Getenv("CBM_GO_MUTATION_CHILD_INFO"), []byte(info), 0600,+ ); err != nil {+ t.Fatal(err)+ }+ continuePath := os.Getenv("CBM_GO_MUTATION_CHILD_CONTINUE")+ deadline := time.Now().Add(20 * time.Second)+ for {+ if _, err := os.Stat(continuePath); err == nil {+ break+ } else if !os.IsNotExist(err) {+ t.Fatal(err)+ }+ if !time.Now().Before(deadline) {+ t.Fatal("mutation child timed out waiting for successor publication")+ }+ time.Sleep(10 * time.Millisecond)+ }+ integrationBytes, err := os.ReadFile(filepath.Join(+ filepath.Dir(executable), integrationsFileName,+ ))+ if err != nil {+ t.Fatal(err)+ }+ if string(integrationBytes) != "integrations:parent-death" {+ t.Fatalf("mutation child sidecar changed: %q", integrationBytes)+ }+ if err := os.WriteFile(+ os.Getenv("CBM_GO_MUTATION_CHILD_SURVIVED"),+ []byte("survived\n"),+ 0600,+ ); err != nil {+ t.Fatal(err)+ }+ return+ }+ if role == "parent" {+ directory := os.Getenv("CBM_GO_MUTATION_CACHE")+ executable := filepath.Join(+ directory, binaryNameForOS(runtime.GOOS),+ )+ runner := func(candidate string, args []string) error {+ command := exec.Command(candidate, args...)+ childEnvironment := make([]string, 0, len(os.Environ())+1)+ for _, entry := range os.Environ() {+ if !strings.HasPrefix(entry, roleEnvironment+"=") {+ childEnvironment = append(childEnvironment, entry)+ }+ }+ command.Env = append(childEnvironment, roleEnvironment+"=child")+ return command.Run()+ }+ if err := execBinaryWithRuntimeLockAndRunner(+ executable,+ []string{+ "-test.run=^TestMutationSnapshotParentDeathLeavesCacheRecoverable$",+ },+ "standard",+ nil,+ runner,+ ); err != nil {+ t.Fatal(err)+ }+ t.Fatal("mutation parent returned before the child was released")+ }++ root := t.TempDir()+ directory := filepath.Join(root, "cache")+ if err := os.Mkdir(directory, 0755); err != nil {+ t.Fatal(err)+ }+ binary := binaryNameForOS(runtime.GOOS)+ stagedExecutable, err := copyRuntimeStage(+ os.Args[0], directory, true, nil,+ )+ if err != nil {+ t.Fatal(err)+ }+ cacheExecutable := filepath.Join(directory, binary)+ if err := os.Rename(stagedExecutable, cacheExecutable); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(+ filepath.Join(directory, integrationsFileName),+ []byte("integrations:parent-death"),+ 0644,+ ); err != nil {+ t.Fatal(err)+ }+ childInfo := filepath.Join(root, "child-info")+ childContinue := filepath.Join(root, "child-continue")+ childSurvived := filepath.Join(root, "child-survived")+ command := exec.Command(+ os.Args[0],+ "-test.run=^TestMutationSnapshotParentDeathLeavesCacheRecoverable$",+ )+ command.Env = append(+ os.Environ(),+ roleEnvironment+"=parent",+ "CBM_GO_MUTATION_CACHE="+directory,+ "CBM_GO_MUTATION_CHILD_INFO="+childInfo,+ "CBM_GO_MUTATION_CHILD_CONTINUE="+childContinue,+ "CBM_GO_MUTATION_CHILD_SURVIVED="+childSurvived,+ )+ var stderr bytes.Buffer+ command.Stderr = &stderr+ if err := command.Start(); err != nil {+ t.Fatal(err)+ }+ waitResult := make(chan error, 1)+ go func() { waitResult <- command.Wait() }()+ parentFinished := false+ childPID := 0+ snapshotExecutable := ""+ defer func() {+ if !parentFinished {+ _ = command.Process.Kill()+ <-waitResult+ }+ if childPID > 0 && runtimeSetProcessAlive(childPID) {+ if child, err := os.FindProcess(childPID); err == nil {+ _ = child.Kill()+ }+ }+ if snapshotExecutable != "" {+ _ = os.RemoveAll(filepath.Dir(snapshotExecutable))+ }+ }()++ deadline := time.Now().Add(10 * time.Second)+ for {+ contents, err := os.ReadFile(childInfo)+ if err == nil {+ lines := strings.Split(strings.TrimSpace(string(contents)), "\n")+ if len(lines) != 2 {+ t.Fatalf("mutation child info = %q", contents)+ }+ childPID, err = strconv.Atoi(lines[0])+ if err != nil {+ t.Fatal(err)+ }+ snapshotExecutable = lines[1]+ break+ }+ if !os.IsNotExist(err) {+ t.Fatal(err)+ }+ select {+ case err := <-waitResult:+ parentFinished = true+ t.Fatalf("mutation parent exited before child start: %v: %s", err, stderr.String())+ default:+ }+ if !time.Now().Before(deadline) {+ t.Fatalf("mutation child did not start: %s", stderr.String())+ }+ time.Sleep(10 * time.Millisecond)+ }+ if filepath.Dir(snapshotExecutable) == directory {+ t.Fatal("mutation child executed from the shared package cache")+ }+ if _, err := os.Stat(filepath.Join(+ directory, runtimeSetLockName,+ )); !os.IsNotExist(err) {+ t.Fatal("mutation parent retained the cache lock while child was running")+ }+ if err := command.Process.Kill(); err != nil {+ t.Fatal(err)+ }+ if err := <-waitResult; err == nil {+ t.Fatal("mutation parent was not hard-killed")+ }+ parentFinished = true+ if !runtimeSetProcessAlive(childPID) {+ t.Fatal("hard-killing the wrapper also stopped the mutation child")+ }++ source := filepath.Join(root, "successor")+ writeTestRuntimeSet(t, source, binary, "successor", "standard")+ if err := publishRuntimeSetWithRecovery(+ source, directory, binary, "standard", verifyTestBinary,+ ); err != nil {+ t.Fatalf("successor publication after parent death failed: %v", err)+ }+ assertRuntimeTag(t, directory, binary, "successor", "standard")+ if err := os.WriteFile(childContinue, []byte("continue\n"), 0600); err != nil {+ t.Fatal(err)+ }+ deadline = time.Now().Add(10 * time.Second)+ for {+ if _, err := os.Stat(childSurvived); err == nil {+ break+ } else if !os.IsNotExist(err) {+ t.Fatal(err)+ }+ if !time.Now().Before(deadline) {+ t.Fatal("snapshot child did not survive successor cache publication")+ }+ time.Sleep(10 * time.Millisecond)+ }+ if _, err := os.Stat(filepath.Join(+ directory, runtimeSetLockName,+ )); !os.IsNotExist(err) {+ t.Fatal("successor recovery left the package-cache lock")+ }+}++func TestRuntimeSetLockReclaimsOnlyDefinitelyDeadOwner(t *testing.T) {+ destination := t.TempDir()+ lockPath := filepath.Join(destination, runtimeSetLockName)+ if err := os.Mkdir(lockPath, 0700); err != nil {+ t.Fatal(err)+ }+ ownerToken := strings.Repeat("a", runtimeSetLockTokenSize*2)+ if err := writeRuntimeSetLockOwner(lockPath, ownerToken); err != nil {+ t.Fatal(err)+ }+ contenderToken := strings.Repeat("b", runtimeSetLockTokenSize*2)+ priorProcessAlive := runtimeSetProcessAlive+ defer func() { runtimeSetProcessAlive = priorProcessAlive }()++ runtimeSetProcessAlive = func(int) bool { return true }+ if runtimeSetTryReclaimLock(lockPath, contenderToken) {+ t.Fatal("runtime-set lock reclaimed an owner that may still be live")+ }+ if _, err := os.Stat(lockPath); err != nil {+ t.Fatalf("live owner's runtime-set lock was damaged: %v", err)+ }++ runtimeSetProcessAlive = func(int) bool { return false }+ if !runtimeSetTryReclaimLock(lockPath, contenderToken) {+ t.Fatal("runtime-set lock did not reclaim a definitely dead owner")+ }+ if _, err := os.Stat(lockPath); !os.IsNotExist(err) {+ t.Fatal("reclaimed dead-owner runtime-set lock still exists")+ }+}++func TestRuntimeSetLockReclaimsOnlyStaleOwnerlessDirectory(t *testing.T) {+ destination := t.TempDir()+ lockPath := filepath.Join(destination, runtimeSetLockName)+ if err := os.Mkdir(lockPath, 0700); err != nil {+ t.Fatal(err)+ }+ contenderToken := strings.Repeat("c", runtimeSetLockTokenSize*2)+ if runtimeSetTryReclaimLock(lockPath, contenderToken) {+ t.Fatal("fresh ownerless runtime-set lock was reclaimed")+ }+ staleTime := time.Now().Add(-runtimeSetOwnerlessStale - time.Second)+ if err := os.Chtimes(lockPath, staleTime, staleTime); err != nil {+ t.Fatal(err)+ }+ if !runtimeSetTryReclaimLock(lockPath, contenderToken) {+ t.Fatal("stale ownerless runtime-set lock was not reclaimed")+ }+ if _, err := os.Stat(lockPath); !os.IsNotExist(err) {+ t.Fatal("reclaimed ownerless runtime-set lock still exists")+ }+}++func TestExpiredLeaseNeverStealsProvenLiveOwner(t *testing.T) {+ destination := t.TempDir()+ lockPath := filepath.Join(destination, runtimeSetLockName)+ record := runtimeSetLockOwnerRecord{+ PID: os.Getpid(), Token: strings.Repeat("a", runtimeSetLockTokenSize*2),+ LeaseExpires: time.Now().Add(-time.Second).UnixMilli(),+ }+ contents, err := json.Marshal(record)+ if err != nil {+ t.Fatal(err)+ }+ contents = append(contents, '\n')+ if err := os.WriteFile(lockPath, contents, 0600); err != nil {+ t.Fatal(err)+ }+ before, err := os.Lstat(lockPath)+ if err != nil {+ t.Fatal(err)+ }+ priorProcessAlive := runtimeSetProcessAlive+ defer func() { runtimeSetProcessAlive = priorProcessAlive }()+ runtimeSetProcessAlive = func(int) bool { return true }+ contender := strings.Repeat("b", runtimeSetLockTokenSize*2)+ if runtimeSetTryReclaimLock(lockPath, contender) {+ t.Fatal("runtime-set lock stole an expired lease from a proven-live owner")+ }+ after, err := os.Lstat(lockPath)+ if err != nil {+ t.Fatalf("live owner's expired lock was removed: %v", err)+ }+ if !runtimeSetSameLockObject(before, after) {+ t.Fatal("live owner's expired lock identity changed")+ }+ afterContents, err := os.ReadFile(lockPath)+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(afterContents, contents) {+ t.Fatalf("live owner's expired lock contents changed: %q", afterContents)+ }+}++func TestLiveLegacyLockIsNotReclaimedSolelyByAge(t *testing.T) {+ destination := t.TempDir()+ lockPath := filepath.Join(destination, runtimeSetLockName)+ if err := os.Mkdir(lockPath, 0700); err != nil {+ t.Fatal(err)+ }+ if err := writeRuntimeSetLockOwner(+ lockPath, strings.Repeat("a", runtimeSetLockTokenSize*2),+ ); err != nil {+ t.Fatal(err)+ }+ stale := time.Now().Add(-runtimeSetLegacyStale - time.Second)+ if err := os.Chtimes(lockPath, stale, stale); err != nil {+ t.Fatal(err)+ }+ priorProcessAlive := runtimeSetProcessAlive+ defer func() { runtimeSetProcessAlive = priorProcessAlive }()+ runtimeSetProcessAlive = func(int) bool { return true }+ if runtimeSetTryReclaimLock(+ lockPath, strings.Repeat("b", runtimeSetLockTokenSize*2),+ ) {+ t.Fatal("live legacy runtime-set lock was reclaimed solely by age")+ }+ if _, err := os.Stat(lockPath); err != nil {+ t.Fatalf("live legacy runtime-set lock was damaged: %v", err)+ }+}++func TestStalledRuntimeLockCreatorNeverDeletesSuccessor(t *testing.T) {+ destination := t.TempDir()+ var successor *runtimeSetLock+ var successorErr error+ priorObserver := runtimeSetLockClaimObserver+ defer func() { runtimeSetLockClaimObserver = priorObserver }()+ runtimeSetLockClaimObserver = func() error {+ runtimeSetLockClaimObserver = nil+ successor, successorErr = acquireRuntimeSetLock(destination)+ return fmt.Errorf("injected stalled creator abort")+ }++ if first, err := acquireRuntimeSetLock(destination); err == nil {+ _ = releaseRuntimeSetLock(first)+ t.Fatal("stalled creator unexpectedly acquired over its successor")+ } else if !strings.Contains(err.Error(), "stalled creator abort") {+ t.Fatalf("stalled creator failed for wrong reason: %v", err)+ }+ if successorErr != nil || successor == nil {+ t.Fatalf("successor did not acquire reclaimed lock: %v", successorErr)+ }+ if _, err := os.Stat(successor.path); err != nil {+ t.Fatalf("failed creator deleted successor lock: %v", err)+ }+ if err := releaseRuntimeSetLock(successor); err != nil {+ t.Fatal(err)+ }+}++func TestRuntimeReadinessRejectsMultiplyLinkedLeaves(t *testing.T) {+ directory := t.TempDir()+ binary := "codebase-memory-mcp"+ writeTestRuntimeSet(t, directory, binary, "linked", "standard")+ if err := os.Link(+ filepath.Join(directory, integrationsFileName),+ filepath.Join(directory, "integrations-hardlink"),+ ); err != nil {+ t.Skipf("filesystem does not support hard links: %v", err)+ }+ if runtimeSetReady(directory, binary, "standard", verifyTestBinary) {+ t.Fatal("runtime set accepted a multiply-linked integrations leaf")+ }+}++func TestWindowsLongRuntimePathPublishesAndBecomesReady(t *testing.T) {+ if runtime.GOOS != "windows" {+ t.Skip("Windows long-path regression")+ }+ root := t.TempDir()+ source := filepath.Join(root, "source")+ destination := filepath.Join(root, "runtime")+ for len(destination) <= 300 {+ destination = filepath.Join(+ destination, "long-runtime-directory-segment",+ )+ }+ if len(destination) <= 260 {+ t.Fatalf("test runtime path is not long: %d", len(destination))+ }+ binary := windowsBinaryName+ writeTestRuntimeSet(t, source, binary, "long-path", "standard")+ if err := publishRuntimeSetWithRecovery(+ source, destination, binary, "standard", verifyTestBinary,+ ); err != nil {+ t.Fatalf("publication under a long Windows runtime path failed: %v", err)+ }+ ready, err := runtimeSetReadyLocked(+ destination, binary, "standard", verifyTestBinary,+ )+ if err != nil {+ t.Fatalf("locked readiness under a long Windows runtime path failed: %v", err)+ }+ if !ready {+ t.Fatal("published long-path Windows runtime set was not ready")+ }+}++func TestOrphanReconciliationRejectsMultiplyLinkedBackupMembers(t *testing.T) {+ directory := t.TempDir()+ binary := "codebase-memory-mcp"+ backup := filepath.Join(+ directory, runtimeBackupPrefix+strings.Repeat("a", 32),+ )+ if err := os.Mkdir(backup, 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(+ filepath.Join(backup, runtimeBackupRetired), nil, 0600,+ ); err != nil {+ t.Fatal(err)+ }+ member := filepath.Join(backup, binary)+ if err := os.WriteFile(member, []byte("binary:old"), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.Link(+ member, filepath.Join(directory, "backup-hardlink-copy"),+ ); err != nil {+ t.Skipf("filesystem does not support hard links: %v", err)+ }++ ready, err := runtimeSetReadyLocked(+ directory, binary, "standard", verifyTestBinary,+ )+ if err == nil || !strings.Contains(+ err.Error(), "unsafe package-cache backup member",+ ) {+ t.Fatalf("unsafe orphan reconciliation = (%v, %v)", ready, err)+ }+ if _, err := os.Stat(backup); err != nil {+ t.Fatalf("unsafe backup was mutated: %v", err)+ }+ if _, err := os.Stat(filepath.Join(+ directory, runtimeSetLockName,+ )); !os.IsNotExist(err) {+ t.Fatal("runtime-set lock survived rejected orphan reconciliation")+ }+}++func TestRuntimeSetLockSerializesProcesses(t *testing.T) {+ const helperEnv = "CBM_GO_RUNTIME_LOCK_HELPER"+ if os.Getenv(helperEnv) == "1" {+ destination := os.Getenv("CBM_GO_RUNTIME_LOCK_DIRECTORY")+ waitingPath := os.Getenv("CBM_GO_RUNTIME_LOCK_WAITING")+ acquiredPath := os.Getenv("CBM_GO_RUNTIME_LOCK_ACQUIRED")+ var waitOnce sync.Once+ runtimeSetLockWaitObserver = func() {+ waitOnce.Do(func() {+ if err := os.WriteFile(waitingPath, []byte("waiting"), 0600); err != nil {+ t.Fatal(err)+ }+ })+ }+ lock, err := acquireRuntimeSetLock(destination)+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(acquiredPath, []byte("acquired"), 0600); err != nil {+ _ = releaseRuntimeSetLock(lock)+ t.Fatal(err)+ }+ if err := releaseRuntimeSetLock(lock); err != nil {+ t.Fatal(err)+ }+ return+ }++ destination := t.TempDir()+ waitingPath := filepath.Join(t.TempDir(), "waiting")+ acquiredPath := filepath.Join(t.TempDir(), "acquired")+ lock, err := acquireRuntimeSetLock(destination)+ if err != nil {+ t.Fatal(err)+ }+ released := false+ defer func() {+ if !released {+ _ = releaseRuntimeSetLock(lock)+ }+ }()++ cmd := exec.Command(os.Args[0], "-test.run=^TestRuntimeSetLockSerializesProcesses$")+ cmd.Env = append(+ os.Environ(),+ helperEnv+"=1",+ "CBM_GO_RUNTIME_LOCK_DIRECTORY="+destination,+ "CBM_GO_RUNTIME_LOCK_WAITING="+waitingPath,+ "CBM_GO_RUNTIME_LOCK_ACQUIRED="+acquiredPath,+ )+ var stdout bytes.Buffer+ var stderr bytes.Buffer+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ waitResult := make(chan error, 1)+ go func() { waitResult <- cmd.Wait() }()+ childFinished := false+ defer func() {+ if !childFinished {+ _ = cmd.Process.Kill()+ <-waitResult+ }+ }()++ deadline := time.Now().Add(5 * time.Second)+ for {+ select {+ case err := <-waitResult:+ childFinished = true+ t.Fatalf(+ "runtime-set lock helper exited before waiting: %v\nstdout: %s\nstderr: %s",+ err,+ stdout.String(),+ stderr.String(),+ )+ default:+ }+ if _, err := os.Stat(waitingPath); err == nil {+ break+ } else if !os.IsNotExist(err) {+ t.Fatal(err)+ }+ if !time.Now().Before(deadline) {+ _ = cmd.Process.Kill()+ <-waitResult+ childFinished = true+ t.Fatalf(+ "child did not report waiting on parent lock\nstdout: %s\nstderr: %s",+ stdout.String(),+ stderr.String(),+ )+ }+ time.Sleep(5 * time.Millisecond)+ }+ if _, err := os.Stat(acquiredPath); err == nil {+ t.Fatal("child acquired the runtime-set lock while the parent owned it")+ } else if !os.IsNotExist(err) {+ t.Fatal(err)+ }+ if err := releaseRuntimeSetLock(lock); err != nil {+ t.Fatal(err)+ }+ released = true+ select {+ case err := <-waitResult:+ childFinished = true+ if err != nil {+ t.Fatalf(+ "runtime-set lock helper failed: %v\nstdout: %s\nstderr: %s",+ err,+ stdout.String(),+ stderr.String(),+ )+ }+ case <-time.After(5 * time.Second):+ _ = cmd.Process.Kill()+ <-waitResult+ childFinished = true+ t.Fatal("child did not acquire the released runtime-set lock")+ }+ if _, err := os.Stat(acquiredPath); err != nil {+ t.Fatalf("child never acquired the released runtime-set lock: %v", err)}- assertTestWindowsPair(t, destination, tag)}diff --git a/pkg/go/cmd/codebase-memory-mcp/pair_lock_other.go b/pkg/go/cmd/codebase-memory-mcp/pair_lock_other.godeleted file mode 100644index 40dc78fe0..000000000--- a/pkg/go/cmd/codebase-memory-mcp/pair_lock_other.go+++ /dev/null@@ -1,10 +0,0 @@-//go:build !windows--package main--// Windows pair publication is never invoked by a non-Windows wrapper. Keeping-// the fallback conservative also lets platform-neutral transaction tests run-// without introducing a second process-liveness policy.-func cbmWindowsLockProcessAlive(pid int) bool {- return pid > 0-}diff --git a/pkg/go/cmd/codebase-memory-mcp/pair_lock_windows.go b/pkg/go/cmd/codebase-memory-mcp/pair_lock_windows.godeleted file mode 100644index d8bb4ecab..000000000--- a/pkg/go/cmd/codebase-memory-mcp/pair_lock_windows.go+++ /dev/null@@ -1,21 +0,0 @@-//go:build windows--package main--import "syscall"--func cbmWindowsLockProcessAlive(pid int) bool {- if pid <= 0 {- return false- }- // PROCESS_QUERY_LIMITED_INFORMATION is sufficient for an existence probe and- // is available on every Windows version supported by the package wrapper.- handle, err := syscall.OpenProcess(0x1000, false, uint32(pid))- if err == nil {- _ = syscall.CloseHandle(handle)- return true- }- // ERROR_INVALID_PARAMETER is the documented result for a process identifier- // that no longer exists. Access denial is conservatively treated as live.- return err != syscall.Errno(87)-}diff --git a/pkg/go/cmd/codebase-memory-mcp/runtime_lock_other.go b/pkg/go/cmd/codebase-memory-mcp/runtime_lock_other.gonew file mode 100644index 000000000..d4c864547--- /dev/null+++ b/pkg/go/cmd/codebase-memory-mcp/runtime_lock_other.go@@ -0,0 +1,34 @@+//go:build !darwin && !linux && !windows++package main++import (+ "fmt"+ "os"+)++func platformCreatePrivateMutationRuntimeDirectory() (string, error) {+ directory, err := os.MkdirTemp("", "codebase-memory-mcp-mutation-*")+ if err != nil {+ return "", err+ }+ status, err := os.Lstat(directory)+ if err != nil || !status.IsDir() || status.Mode()&os.ModeSymlink != 0 ||+ status.Mode().Perm()&0077 != 0 {+ _ = os.RemoveAll(directory)+ return "", fmt.Errorf(+ "could not create an owner-private mutation runtime snapshot",+ )+ }+ return directory, nil+}++// Unsupported wrapper platforms never reclaim a syntactically valid owner by+// PID. Ownerless stale locks remain recoverable through the generic age rule.+func platformRuntimeSetLockProcessAlive(pid int) bool {+ return pid > 0+}++func platformRuntimeSetFileLinkCountOne(_ string, _ os.FileInfo) bool {+ return true+}diff --git a/pkg/go/cmd/codebase-memory-mcp/runtime_lock_unix.go b/pkg/go/cmd/codebase-memory-mcp/runtime_lock_unix.gonew file mode 100644index 000000000..0c8158b2d--- /dev/null+++ b/pkg/go/cmd/codebase-memory-mcp/runtime_lock_unix.go@@ -0,0 +1,40 @@+//go:build darwin || linux++package main++import (+ "fmt"+ "os"+ "syscall"+)++func platformCreatePrivateMutationRuntimeDirectory() (string, error) {+ directory, err := os.MkdirTemp("", "codebase-memory-mcp-mutation-*")+ if err != nil {+ return "", err+ }+ status, err := os.Lstat(directory)+ if err != nil || !status.IsDir() || status.Mode()&os.ModeSymlink != 0 ||+ status.Mode().Perm()&0077 != 0 {+ _ = os.RemoveAll(directory)+ return "", fmt.Errorf(+ "could not create an owner-private mutation runtime snapshot",+ )+ }+ return directory, nil+}++func platformRuntimeSetLockProcessAlive(pid int) bool {+ if pid <= 0 {+ return false+ }+ err := syscall.Kill(pid, 0)+ // Only ESRCH proves the owner is gone. Permission denial and every other+ // result are conservatively treated as evidence that it may still be live.+ return err != syscall.ESRCH+}++func platformRuntimeSetFileLinkCountOne(_ string, info os.FileInfo) bool {+ status, ok := info.Sys().(*syscall.Stat_t)+ return ok && status.Nlink == 1+}diff --git a/pkg/go/cmd/codebase-memory-mcp/runtime_lock_windows.go b/pkg/go/cmd/codebase-memory-mcp/runtime_lock_windows.gonew file mode 100644index 000000000..3fa233c5a--- /dev/null+++ b/pkg/go/cmd/codebase-memory-mcp/runtime_lock_windows.go@@ -0,0 +1,197 @@+//go:build windows++package main++import (+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "syscall"+ "unsafe"+)++const windowsFilePersistentACLs = 0x00000008++var (+ windowsAdvapi32 = syscall.NewLazyDLL("advapi32.dll")+ windowsKernel32 = syscall.NewLazyDLL("kernel32.dll")+ windowsConvertStringSecurityDescriptor = windowsAdvapi32.NewProc(+ "ConvertStringSecurityDescriptorToSecurityDescriptorW",+ )+ windowsGetVolumeInformationByHandle = windowsKernel32.NewProc(+ "GetVolumeInformationByHandleW",+ )+)++func windowsExtendedPath(path string) (string, error) {+ absolute, err := filepath.Abs(path)+ if err != nil {+ return "", err+ }+ if strings.HasPrefix(absolute, `\\?\`) {+ return absolute, nil+ }+ if strings.HasPrefix(absolute, `\\.\`) {+ return "", fmt.Errorf("refusing Windows device path: %s", path)+ }+ if strings.HasPrefix(absolute, `\\`) {+ return `\\?\UNC\` + strings.TrimPrefix(absolute, `\\`), nil+ }+ return `\\?\` + absolute, nil+}++func windowsPrivateDirectorySecurityDescriptor() (uintptr, error) {+ token, err := syscall.OpenCurrentProcessToken()+ if err != nil {+ return 0, err+ }+ defer token.Close()+ user, err := token.GetTokenUser()+ if err != nil {+ return 0, err+ }+ userSID, err := user.User.Sid.String()+ if err != nil {+ return 0, err+ }+ // Protected DACL: the explicit current user owns the directory and that+ // user, LocalSystem, and administrators have full control.+ // Object/container inheritance applies the same policy to every runtime+ // leaf created inside the snapshot.+ sddl, err := syscall.UTF16PtrFromString(+ "O:" + userSID ++ "D:P(A;OICI;FA;;;" + userSID + ")" ++ "(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)",+ )+ if err != nil {+ return 0, err+ }+ var descriptor uintptr+ result, _, callErr := windowsConvertStringSecurityDescriptor.Call(+ uintptr(unsafe.Pointer(sddl)),+ 1,+ uintptr(unsafe.Pointer(&descriptor)),+ 0,+ )+ if result == 0 {+ if callErr != nil && callErr != syscall.Errno(0) {+ return 0, callErr+ }+ return 0, syscall.EINVAL+ }+ return descriptor, nil+}++func windowsDirectoryVolumePersistsACLs(path string) error {+ directory, err := os.Open(path)+ if err != nil {+ return err+ }+ defer directory.Close()+ var flags uint32+ result, _, callErr := windowsGetVolumeInformationByHandle.Call(+ directory.Fd(),+ 0,+ 0,+ 0,+ 0,+ uintptr(unsafe.Pointer(&flags)),+ 0,+ 0,+ )+ if result == 0 {+ if callErr != nil && callErr != syscall.Errno(0) {+ return callErr+ }+ return syscall.EINVAL+ }+ if flags&windowsFilePersistentACLs == 0 {+ return fmt.Errorf("temporary volume does not persist Windows ACLs")+ }+ return nil+}++func platformCreatePrivateMutationRuntimeDirectory() (string, error) {+ descriptor, err := windowsPrivateDirectorySecurityDescriptor()+ if err != nil {+ return "", err+ }+ defer syscall.LocalFree(syscall.Handle(descriptor))+ attributes := syscall.SecurityAttributes{+ Length: uint32(unsafe.Sizeof(syscall.SecurityAttributes{})),+ SecurityDescriptor: descriptor,+ }+ // The protected child DACL makes the snapshot owner-private on a volume+ // with persistent ACLs. It cannot prevent a principal that already holds+ // FILE_DELETE_CHILD on a hostile shared TEMP parent from replacing the+ // pathname, so the supported boundary remains a normal per-user TEMP root.+ for attempt := 0; attempt < 128; attempt++ {+ token, err := runtimeSetLockToken()+ if err != nil {+ return "", err+ }+ directory := filepath.Join(+ os.TempDir(), "codebase-memory-mcp-mutation-"+token,+ )+ extended, err := windowsExtendedPath(directory)+ if err != nil {+ return "", err+ }+ pointer, err := syscall.UTF16PtrFromString(extended)+ if err != nil {+ return "", err+ }+ if err := syscall.CreateDirectory(pointer, &attributes); err != nil {+ if err == syscall.ERROR_ALREADY_EXISTS {+ continue+ }+ return "", err+ }+ if err := windowsDirectoryVolumePersistsACLs(directory); err != nil {+ _ = os.RemoveAll(directory)+ return "", err+ }+ return directory, nil+ }+ return "", fmt.Errorf("could not reserve a private mutation runtime snapshot")+}++func platformRuntimeSetLockProcessAlive(pid int) bool {+ if pid <= 0 {+ return false+ }+ if uint64(pid) > uint64(^uint32(0)) {+ // An out-of-range value cannot be probed without truncation, so it is not+ // evidence that an otherwise valid owner is dead.+ return true+ }+ // PROCESS_QUERY_LIMITED_INFORMATION is sufficient for an existence probe and+ // is available on every Windows version supported by the package wrapper.+ handle, err := syscall.OpenProcess(0x1000, false, uint32(pid))+ if err == nil {+ _ = syscall.CloseHandle(handle)+ return true+ }+ // ERROR_INVALID_PARAMETER is the documented result for a process identifier+ // that no longer exists. Access denial is conservatively treated as live.+ return err != syscall.Errno(87)+}++func platformRuntimeSetFileLinkCountOne(path string, _ os.FileInfo) bool {+ // os.Open applies Go's absolute long-path handling before CreateFileW.+ // Passing an ordinary UTF-16 path directly to syscall.CreateFile would+ // reject otherwise valid custom cache paths beyond MAX_PATH.+ file, err := os.Open(path)+ if err != nil {+ return false+ }+ defer file.Close()+ var information syscall.ByHandleFileInformation+ if err := syscall.GetFileInformationByHandle(+ syscall.Handle(file.Fd()), &information,+ ); err != nil {+ return false+ }+ return information.NumberOfLinks == 1+}diff --git a/pkg/homebrew/Formula/codebase-memory-mcp.rb b/pkg/homebrew/Formula/codebase-memory-mcp.rbindex 98736781c..715bd00d8 100644--- a/pkg/homebrew/Formula/codebase-memory-mcp.rb+++ b/pkg/homebrew/Formula/codebase-memory-mcp.rb@@ -28,6 +28,7 @@ class CodebaseMemoryMcp < Formuladef installbin.install "codebase-memory-mcp"+ (share/"codebase-memory-mcp").install "cbm-integrations.json"# Third-party attribution bundle (present in archives since v0.8.1)doc.install "THIRD_PARTY_NOTICES.md" if File.exist?("THIRD_PARTY_NOTICES.md")end@@ -45,5 +46,6 @@ class CodebaseMemoryMcp < Formulatest doassert_match "codebase-memory-mcp", shell_output("#{bin}/codebase-memory-mcp --version")+ assert_path_exists share/"codebase-memory-mcp/cbm-integrations.json"endenddiff --git a/pkg/npm/README.md b/pkg/npm/README.mdindex e9ef2b468..c64df22be 100644--- a/pkg/npm/README.md+++ b/pkg/npm/README.md@@ -5,9 +5,9 @@[](https://github.com/DeusData/codebase-memory-mcp/blob/main/LICENSE)[](https://github.com/DeusData/codebase-memory-mcp/releases/latest)-**The fastest and most efficient code intelligence engine for AI coding agents.** Full-indexes an average repository in milliseconds, the Linux kernel (28M LOC, 75K files) in 3 minutes. Answers structural queries in under 1ms. Ships as a single static binary — this package downloads and runs it automatically.+**The fastest and most efficient code intelligence engine for AI coding agents.** Full-indexes an average repository in milliseconds, the Linux kernel (28M LOC, 75K files) in 3 minutes. Answers structural queries in under 1ms. This npm wrapper downloads, verifies, and caches the selected native runtime set: the executable, its authenticated integration asset, and—when requested—the content-addressed UI pack.-High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-sitter/) AST analysis across 159 languages — producing a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. 14 MCP tools. Zero dependencies. Plug and play across 43 automatic/conditional client surfaces.+High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-sitter/) AST analysis across 159 languages — producing a persistent knowledge graph of functions, classes, call chains, HTTP routes, and cross-service links. 14 MCP tools. No hosted service or API key; this package requires Node.js to manage and launch the cached native runtime set. Plug and play across 43 automatic/conditional client surfaces.## Installation@@ -15,7 +15,13 @@ High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-sinpm install -g codebase-memory-mcp```-The binary for your platform is downloaded automatically at install time. Then configure your coding agents:+The standard runtime set for your platform is downloaded automatically at install time. To select the UI runtime set and its verified frontend pack, set `CBM_VARIANT=ui` while installing and when invoking the wrapper:++```bash+CBM_VARIANT=ui npm install -g codebase-memory-mcp+```++Then configure your coding agents:```bashcodebase-memory-mcp install@@ -26,7 +32,7 @@ Restart your agent. Say **"Index this project"** — done.## Why codebase-memory-mcp- **Extreme indexing speed** — Linux kernel (28M LOC, 75K files) in 3 minutes. RAM-first pipeline with LZ4 compression and in-memory SQLite.-- **Plug and play** — single static binary for macOS (arm64/amd64), Linux (arm64/amd64), and Windows (amd64). No Docker, no runtime dependencies, no API keys.+- **Plug and play** — verified native runtime sets for macOS (arm64/amd64), Linux (arm64/amd64), and Windows (arm64/amd64). No Docker or API keys; Node.js owns package download, cache repair, and launch.- **159 languages** — vendored tree-sitter grammars compiled into the binary. Nothing to install, nothing that breaks.- **120x fewer tokens** — 5 structural queries: ~3,400 tokens vs ~412,000 via file-by-file search.- **43 supported automatic/conditional client surfaces** — `install` configures the appropriate MCP, durable-context, and documented hook surfaces without widening client permissions.@@ -44,7 +50,7 @@ Restart your agent. Say **"Index this project"** — done.|---------|-------------|| macOS | arm64, amd64 || Linux | arm64, amd64 |-| Windows | amd64 |+| Windows | arm64, amd64 |## Usagediff --git a/pkg/npm/bin.js b/pkg/npm/bin.jsindex 8b7d82e09..e467981be 100644--- a/pkg/npm/bin.js+++ b/pkg/npm/bin.js@@ -4,30 +4,34 @@// If the binary is missing (e.g. --ignore-scripts), attempts a one-time download.const path = require('path');-const fs = require('fs');-const { spawnSync } = require('child_process');+const os = require('os');+const { spawn, spawnSync } = require('child_process');+const {+ acquireRuntimeLock,+ refreshRuntimeLock,+ releaseRuntimeLock,+ runtimeSetReady,+ runtimeSetReadyLocked,+} = require('./install.js');const isWindows = process.platform === 'win32';-// npm is a portable one-shot wrapper. Every platform ships exactly ONE binary,-// so the cached file is the executed file — there is no launcher pair to keep-// in sync and no adjacent payload to validate.+const variant = (process.env.CBM_VARIANT || '').toLowerCase() === 'ui'+ ? 'ui'+ : 'standard';+// npm is a portable one-shot wrapper. Every platform ships exactly one binary,+// which is executed directly beside its authenticated runtime sidecars.const binName = isWindows ? 'codebase-memory-mcp.exe' : 'codebase-memory-mcp';-const binPath = path.join(__dirname, 'bin', binName);+const binDir = path.join(__dirname, 'bin', variant);+const binPath = path.join(binDir, binName);const executionPath = binPath;-const cacheReady = () => {- if (!fs.existsSync(binPath)) {- return false;- }- if (!isWindows) return true;- // A cached Windows binary that cannot report its own version is not usable.- const probe = spawnSync(binPath, ['--version'], {- stdio: 'ignore',- timeout: 15_000,- windowsHide: true,- });- return !probe.error && probe.status === 0;-};+const cacheReady = () => runtimeSetReadyLocked(binDir, binName, variant);+function main() {+const requestedMutation = runtimeMutationAction(process.argv.slice(2));+if (requestedMutation === 'update') {+ printUpdateGuidance();+ process.exit(2);+}if (!cacheReady()) {// Binary missing — try running the install script (handles --ignore-scripts case)process.stderr.write('codebase-memory-mcp: binary not found, downloading...\n');@@ -43,17 +47,105 @@ if (!cacheReady()) {}}-function portableMutationAction(args) {+function runtimeMutationAction(args) {for (const argument of args) {- if (['cli', 'hook-augment', 'config', 'install', '--help', '-h', '--version'].includes(argument)) {+ if (argument === '--help' || argument === '-h' || argument === '--version') {return null;}- if (argument === 'update' || argument === 'uninstall') return argument;+ if (argument.startsWith('-')) continue;+ if (argument === 'install' || argument === 'update' || argument === 'uninstall') {+ return argument;+ }+ if (argument === 'cli' || argument === 'hook-augment' || argument === 'config') {+ return null;+ }+ return null;}return null;}-const result = spawnSync(executionPath, process.argv.slice(2), {+function defaultManagedInstallDir() {+ if (!isWindows) return path.join(os.homedir(), '.local', 'bin');+ const localAppData = process.env.LOCALAPPDATA ||+ path.join(os.homedir(), 'AppData', 'Local');+ return path.join(localAppData, 'Programs', 'codebase-memory-mcp');+}++function nativeArgs(args) {+ const result = [...args];+ if (runtimeMutationAction(result) === 'uninstall' &&+ !result.some((argument) => argument === '--dir' || argument.startsWith('--dir='))) {+ result.push('--dir', defaultManagedInstallDir());+ }+ return result;+}++function printUpdateGuidance() {+ process.stderr.write(+ 'This npm copy is maintained by npm. Update it with ' ++ '"npm install codebase-memory-mcp@latest" (add -g for a global install). ' ++ 'For a managed standalone installation, run ' ++ '"codebase-memory-mcp install --yes".\n',+ );+}++const forwardedArgs = nativeArgs(process.argv.slice(2));+const mutation = requestedMutation;++if (mutation === 'install' || mutation === 'uninstall') {+ const lock = acquireRuntimeLock(binDir);+ let heartbeatError = null;+ try {+ refreshRuntimeLock(lock);+ if (!runtimeSetReady(binDir, binName, variant)) {+ throw new Error('cached runtime assets changed before mutation launch');+ }+ } catch (error) {+ try { releaseRuntimeLock(lock); } catch (_) { /* preserve first error */ }+ process.stderr.write(`codebase-memory-mcp: ${error.message}\n`);+ process.exit(1);+ }+ let child = null;+ const heartbeat = setInterval(() => {+ try {+ refreshRuntimeLock(lock);+ } catch (error) {+ heartbeatError = error;+ if (child) child.kill();+ }+ }, 20_000);+ child = spawn(executionPath, forwardedArgs, {+ stdio: 'inherit',+ windowsHide: false,+ });+ child.on('error', (error) => {+ clearInterval(heartbeat);+ try { releaseRuntimeLock(lock); } catch (_) { /* report spawn error */ }+ process.stderr.write(`codebase-memory-mcp: ${error.message}\n`);+ process.exit(1);+ });+ child.on('close', (status) => {+ clearInterval(heartbeat);+ let releaseError = heartbeatError;+ try { releaseRuntimeLock(lock); } catch (error) { releaseError ||= error; }+ if (releaseError) {+ process.stderr.write(`codebase-memory-mcp: ${releaseError.message}\n`);+ process.exit(1);+ }+ if (isWindows && status !== 0 && mutation === 'uninstall') {+ process.stderr.write(+ 'This npm Windows copy is portable. Use "npm uninstall codebase-memory-mcp" ' ++ 'for package maintenance (add -g for a global install). ' ++ 'To create or repair a managed standalone installation, run ' ++ '"codebase-memory-mcp install --yes".\n',+ );+ }+ process.exit(status ?? 0);+ });+ return;+}++const result = spawnSync(executionPath, forwardedArgs, {stdio: 'inherit',windowsHide: false,});@@ -63,19 +155,7 @@ if (result.error) {process.exit(1);}-const mutation = isWindows && result.status !== 0- ? portableMutationAction(process.argv.slice(2))- : null;-if (mutation) {- const packageCommand = mutation === 'update'- ? 'npm install codebase-memory-mcp@latest'- : 'npm uninstall codebase-memory-mcp';- process.stderr.write(- `This npm Windows copy is portable. Use "${packageCommand}" for package ` +- 'maintenance (add -g for a global install), or run ' +- '"codebase-memory-mcp install --yes" once for a managed install with its ' +- 'own install.ps1 for updates.\n',- );+process.exit(result.status ?? 0);}-process.exit(result.status ?? 0);+main();diff --git a/pkg/npm/install.js b/pkg/npm/install.jsindex 2c3ea9b6c..892a6d314 100644--- a/pkg/npm/install.js+++ b/pkg/npm/install.js@@ -13,28 +13,39 @@ const { pipeline } = require('stream');const REPO = 'DeusData/codebase-memory-mcp';const VERSION = require('./package.json').version;-const BIN_DIR = path.join(__dirname, 'bin');+const BIN_ROOT = path.join(__dirname, 'bin');const MAX_REDIRECTS = 5;const DOWNLOAD_HOP_TIMEOUT_MS = 120_000;const CANDIDATE_TIMEOUT_MS = 15_000;const MAX_CHECKSUM_MANIFEST_BYTES = 1024 * 1024;const WINDOWS_BINARY_NAME = 'codebase-memory-mcp.exe';+const INTEGRATIONS_NAME = 'cbm-integrations.json';+const UI_PACK_PATTERN = /^cbm-ui-[0-9a-f]{64}\.pack$/;const UNIX_ARCHIVE_NAMES = ['codebase-memory-mcp',+ INTEGRATIONS_NAME,'LICENSE','install.sh','THIRD_PARTY_NOTICES.md',];const WINDOWS_ARCHIVE_NAMES = [WINDOWS_BINARY_NAME,+ INTEGRATIONS_NAME,'LICENSE','install.ps1','THIRD_PARTY_NOTICES.md',];-const WINDOWS_PAIR_LOCK_NAME = '.codebase-memory-mcp-pair.lock';-const WINDOWS_PAIR_LOCK_WAIT_MS = 45_000;-const WINDOWS_PAIR_OWNERLESS_STALE_MS = 30_000;-const WINDOWS_PAIR_LOCK_POLL_MS = 25;+const RUNTIME_LOCK_NAME = '.codebase-memory-mcp-runtime.lock';+const RUNTIME_LOCK_WAIT_MS = 45_000;+const RUNTIME_OWNERLESS_STALE_MS = 30_000;+const RUNTIME_LOCK_LEASE_MS = 300_000;+const RUNTIME_LOCK_HEARTBEAT_MS = 20_000;+const RUNTIME_LEGACY_STALE_MS = 3_600_000;+const RUNTIME_LOCK_POLL_MS = 25;+const RUNTIME_BACKUP_PREFIX = '.cbm-runtime-backup-';+const RUNTIME_BACKUP_DIRECTORY_PATTERN = /^\.cbm-runtime-backup-[0-9a-f]{32}$/;+const RUNTIME_BACKUP_RETIRED_MARKER = '.retirement-complete';+const RUNTIME_BACKUP_CLEANUP_MARKER = '.cleanup-only';const SLEEP_WORD = new Int32Array(new SharedArrayBuffer(4));function getPlatform() {@@ -69,7 +80,7 @@ function validateUrl(rawUrl) {return parsed.href;}-function validateExactTarMemberListing(listing, expectedNames) {+function validateExactTarMemberListing(listing, expectedNames, ui = false) {if (listing.includes('\0')) {throw new Error('tar member listing contains a NUL byte');}@@ -77,34 +88,61 @@ function validateExactTarMemberListing(listing, expectedNames) {if (members[members.length - 1] === '') members.pop();const expected = new Set(expectedNames);const seen = new Set();+ let uiPackName = null;for (const member of members) {- if (!member || !expected.has(member) || seen.has(member)) {+ const isUiPack = ui && UI_PACK_PATTERN.test(member);+ if (!member || (!expected.has(member) && !isUiPack) || seen.has(member) ||+ (isUiPack && uiPackName !== null)) {throw new Error(`archive contains an unexpected or duplicate root member: ${JSON.stringify(member)}`);}seen.add(member);+ if (isUiPack) uiPackName = member;}- if (members.length !== expectedNames.length || seen.size !== expected.size) {+ const expectedCount = expectedNames.length + (ui ? 1 : 0);+ if (members.length !== expectedCount || seen.size !== expectedCount ||+ expectedNames.some((name) => !seen.has(name)) || (ui && uiPackName === null)) {throw new Error(- `archive must contain exactly these root files: ${expectedNames.join(', ')}`,+ `archive must contain exactly these root files${ui ? ' plus one content-addressed UI pack' : ''}: ${expectedNames.join(', ')}`,);}+ return uiPackName;+}++function validateRegularTarMemberListing(listing, expectedCount) {+ const entries = listing.split(/\r?\n/).filter((line) => line.length > 0);+ if (entries.length !== expectedCount ||+ entries.some((line) => line[0] !== '-')) {+ throw new Error('archive members must be independent regular files (no links)');+ }}function extractExactTarArchive(- archivePath, destPath, expectedNames, targetName, runFile = execFileSync,+ archivePath, destPath, expectedNames, targetNames, ui = false,+ runFile = execFileSync,) {const listing = runFile('tar', ['-tzf', archivePath], {encoding: 'utf8',maxBuffer: MAX_CHECKSUM_MANIFEST_BYTES,windowsHide: true,});- validateExactTarMemberListing(listing, expectedNames);- // Extract only the fixed root executable. Even a malformed tar implementation- // cannot write an unvalidated companion member outside the private temp tree.- runFile('tar', ['-xzf', archivePath, '-C', destPath, targetName], {+ const uiPackName = validateExactTarMemberListing(listing, expectedNames, ui);+ const verboseListing = runFile('tar', ['-tvzf', archivePath], {+ encoding: 'utf8',+ maxBuffer: MAX_CHECKSUM_MANIFEST_BYTES,+ windowsHide: true,+ });+ validateRegularTarMemberListing(+ verboseListing, expectedNames.length + (ui ? 1 : 0),+ );+ const names = Array.isArray(targetNames) ? [...targetNames] : [targetNames];+ if (uiPackName !== null) names.push(uiPackName);+ // Extract only the authenticated runtime set. Even a malformed tar+ // implementation cannot write an unvalidated non-runtime member.+ runFile('tar', ['-xzf', archivePath, '-C', destPath, ...names], {stdio: 'inherit',windowsHide: true,});+ return names;}function downloadHop(url, dest, maxBytes) {@@ -204,7 +242,7 @@ function parseExpectedChecksum(manifest, archiveName) {}function verifyCandidate(candidatePath) {- execFileSync(candidatePath, ['--version'], {+ execFileSync(candidatePath, ['--verify-runtime-assets'], {stdio: ['ignore', 'pipe', 'pipe'],timeout: CANDIDATE_TIMEOUT_MS,windowsHide: true,@@ -227,21 +265,101 @@ function fileSha256(candidatePath) {return digest.digest('hex');}-function filesEqualSha256(leftPath, rightPath) {+function sleepSync(milliseconds) {+ Atomics.wait(SLEEP_WORD, 0, 0, milliseconds);+}++function runtimeVariant(env = process.env) {+ return (env.CBM_VARIANT || '').toLowerCase() === 'ui' ? 'ui' : 'standard';+}++function cacheDirForVariant(variant) {+ return path.join(BIN_ROOT, variant);+}++function requireSafeRuntimeDirectory(directory) {+ const status = fs.lstatSync(directory);+ if (!status.isDirectory() || status.isSymbolicLink()) {+ throw new Error(`refusing unsafe package-cache directory: ${directory}`);+ }+}++function regularFile(pathname) {try {- const left = fs.statSync(leftPath);- const right = fs.statSync(rightPath);- return left.isFile()- && right.isFile()- && left.size === right.size- && fileSha256(leftPath) === fileSha256(rightPath);+ const status = fs.lstatSync(pathname);+ return status.isFile() && !status.isSymbolicLink() && status.nlink === 1;} catch (_) {return false;}}-function sleepSync(milliseconds) {- Atomics.wait(SLEEP_WORD, 0, 0, milliseconds);+function uiPackMatchesDigest(directory, name) {+ try {+ const expected = name.slice('cbm-ui-'.length, -'.pack'.length);+ return fileSha256(path.join(directory, name)) === expected;+ } catch (_) {+ return false;+ }+}++function runtimeSetNames(directory, binaryName, variant) {+ if (!regularFile(path.join(directory, binaryName)) ||+ !regularFile(path.join(directory, INTEGRATIONS_NAME))) {+ return null;+ }+ let packLikeNames;+ try {+ packLikeNames = fs.readdirSync(directory)+ .filter((name) => name.startsWith('cbm-ui-') && name.endsWith('.pack'));+ } catch (_) {+ return null;+ }+ const validPackNames = packLikeNames.filter(+ (name) => UI_PACK_PATTERN.test(name) &&+ regularFile(path.join(directory, name)) &&+ uiPackMatchesDigest(directory, name),+ );+ if (variant === 'ui') {+ if (packLikeNames.length !== 1 || validPackNames.length !== 1) {+ return null;+ }+ } else if (packLikeNames.length !== 0) {+ return null;+ }+ return [+ INTEGRATIONS_NAME,+ ...(variant === 'ui' ? validPackNames : []),+ binaryName,+ ];+}++function runtimeSetReady(+ directory, binaryName, variant, verifier = verifyCandidate,+) {+ if (runtimeSetNames(directory, binaryName, variant) === null) return false;+ try {+ verifier(path.join(directory, binaryName));+ return true;+ } catch (_) {+ return false;+ }+}++function runtimeSetReadyLocked(+ directory, binaryName, variant, verifier = verifyCandidate,+) {+ fs.mkdirSync(directory, { recursive: true, mode: 0o755 });+ requireSafeRuntimeDirectory(directory);+ const lock = acquireRuntimeLock(directory);+ try {+ refreshRuntimeLock(lock);+ reconcileRuntimeBackups(+ directory, binaryName, variant, verifier, lock,+ );+ return runtimeSetReady(directory, binaryName, variant, verifier);+ } finally {+ releaseRuntimeLock(lock);+ }}function processIsAlive(pid) {@@ -256,33 +374,69 @@ function processIsAlive(pid) {}}-function readBinaryLockOwner(lockPath) {+function lockPathStatus(lockPath) {+ try {+ return fs.lstatSync(lockPath, { bigint: true });+ } catch (_) {+ return null;+ }+}++function sameLockObject(left, right) {+ return left !== null && right !== null &&+ left.dev === right.dev && left.ino === right.ino &&+ left.isFile() === right.isFile() && left.isDirectory() === right.isDirectory();+}++function readRuntimeLockOwner(lockPath) {try {+ const status = fs.lstatSync(lockPath);+ if (status.isSymbolicLink() || (!status.isFile() && !status.isDirectory())) {+ return null;+ }+ const ownerPath = status.isDirectory()+ ? path.join(lockPath, 'owner.json')+ : lockPath;const owner = JSON.parse(- fs.readFileSync(path.join(lockPath, 'owner.json'), 'utf8'),+ fs.readFileSync(ownerPath, 'utf8'),);if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0 ||typeof owner.token !== 'string' || !/^[0-9a-f]{32}$/.test(owner.token)) {return null;}- return owner;+ const leaseExpiresMs = Number.isSafeInteger(owner.lease_expires_ms)+ ? owner.lease_expires_ms+ : null;+ return { ...owner, lease_expires_ms: leaseExpiresMs };} catch (_) {return null;}}-function tryReclaimBinaryLock(lockPath, contenderToken) {- let reclaim = false;- const owner = readBinaryLockOwner(lockPath);+function restoreDisplacedRuntimeLock(reclaimed, lockPath, status) {+ if (!status || !status.isFile()) return;+ try {+ fs.linkSync(reclaimed, lockPath);+ fs.unlinkSync(reclaimed);+ } catch (_) {+ // A new owner already holds the canonical name. Preserve the displaced+ // object for its owner to diagnose; never delete an unverified successor.+ }+}++function tryReclaimRuntimeLock(lockPath, contenderToken) {+ const observedStatus = lockPathStatus(lockPath);+ if (observedStatus === null) return true;+ if (observedStatus.isSymbolicLink() ||+ (!observedStatus.isFile() && !observedStatus.isDirectory())) {+ return false;+ }+ let reclaim;+ const owner = readRuntimeLockOwner(lockPath);if (owner) {reclaim = !processIsAlive(owner.pid);} else {- try {- const age = Date.now() - fs.statSync(lockPath).mtimeMs;- reclaim = age >= WINDOWS_PAIR_OWNERLESS_STALE_MS;- } catch (_) {- return true; // The owner released it between observation and inspection.- }+ reclaim = Date.now() - Number(observedStatus.mtimeMs) >= RUNTIME_OWNERLESS_STALE_MS;}if (!reclaim) return false;@@ -293,152 +447,467 @@ function tryReclaimBinaryLock(lockPath, contenderToken) {if (err.code === 'ENOENT') return true;return false;}- fs.rmSync(reclaimed, { recursive: true, force: true });+ const movedStatus = lockPathStatus(reclaimed);+ if (!sameLockObject(observedStatus, movedStatus)) {+ restoreDisplacedRuntimeLock(reclaimed, lockPath, movedStatus);+ return false;+ }+ const movedOwner = readRuntimeLockOwner(reclaimed);+ const stillReclaimable = movedOwner === null+ ? Date.now() - Number(movedStatus.mtimeMs) >= RUNTIME_OWNERLESS_STALE_MS+ : !processIsAlive(movedOwner.pid);+ if (!stillReclaimable) {+ restoreDisplacedRuntimeLock(reclaimed, lockPath, movedStatus);+ return false;+ }+ if (movedStatus.isDirectory()) {+ // Legacy directory locks are accepted only as real, non-symlink+ // directories, then quarantined and removed after identity revalidation.+ fs.rmSync(reclaimed, { recursive: true, force: true });+ } else {+ fs.unlinkSync(reclaimed);+ }return true;}-function acquireWindowsBinaryLock(destDir) {- const lockPath = path.join(destDir, WINDOWS_PAIR_LOCK_NAME);+function writeRuntimeLockOwner(fd, token) {+ const record = Buffer.from(`${JSON.stringify({+ pid: process.pid,+ token,+ lease_expires_ms: Date.now() + RUNTIME_LOCK_LEASE_MS,+ })}\n`, 'utf8');+ fs.ftruncateSync(fd, 0);+ let offset = 0;+ while (offset < record.length) {+ offset += fs.writeSync(fd, record, offset, record.length - offset, offset);+ }+ fs.fsyncSync(fd);+}++function assertRuntimeLockOwner(lock) {+ const descriptorStatus = fs.fstatSync(lock.fd, { bigint: true });+ const canonicalStatus = lockPathStatus(lock.lockPath);+ const owner = readRuntimeLockOwner(lock.lockPath);+ if (!sameLockObject(descriptorStatus, canonicalStatus) || !owner ||+ owner.token !== lock.token || owner.pid !== process.pid) {+ throw new Error('package-cache publication lock ownership changed');+ }+}++function refreshRuntimeLock(lock) {+ assertRuntimeLockOwner(lock);+ writeRuntimeLockOwner(lock.fd, lock.token);+ assertRuntimeLockOwner(lock);+}++function acquireRuntimeLock(destDir, beforeClaimPublish = null) {+ const lockPath = path.join(destDir, RUNTIME_LOCK_NAME);const token = crypto.randomBytes(16).toString('hex');- const deadline = Date.now() + WINDOWS_PAIR_LOCK_WAIT_MS;+ const claimPath = `${lockPath}.claim-${token}`;+ const deadline = Date.now() + RUNTIME_LOCK_WAIT_MS;for (;;) {+ let fd = null;try {- fs.mkdirSync(lockPath, { mode: 0o700 });+ fd = fs.openSync(claimPath, 'wx', 0o600);try {- fs.writeFileSync(- path.join(lockPath, 'owner.json'),- `${JSON.stringify({ pid: process.pid, token })}\n`,- { encoding: 'utf8', flag: 'wx', mode: 0o600 },- );+ writeRuntimeLockOwner(fd, token);+ if (beforeClaimPublish) beforeClaimPublish(lockPath);+ fs.linkSync(claimPath, lockPath);+ fs.unlinkSync(claimPath);+ const descriptorStatus = fs.fstatSync(fd, { bigint: true });+ if (!sameLockObject(descriptorStatus, lockPathStatus(lockPath))) {+ throw new Error('package-cache publication lock ownership changed');+ }} catch (err) {- fs.rmSync(lockPath, { recursive: true, force: true });+ fs.closeSync(fd);+ fd = null;+ try { fs.unlinkSync(claimPath); } catch (_) { /* unique claim is gone */ }throw err;}- return { lockPath, token };+ return { lockPath, token, fd };} catch (err) {+ if (fd !== null) {+ try { fs.closeSync(fd); } catch (_) { /* already closed */ }+ }if (err.code !== 'EEXIST') throw err;- if (tryReclaimBinaryLock(lockPath, token)) continue;+ if (tryReclaimRuntimeLock(lockPath, token)) continue;if (Date.now() >= deadline) {- throw new Error('timed out waiting for Windows package-cache publication lock');+ throw new Error('timed out waiting for package-cache publication lock');}- sleepSync(WINDOWS_PAIR_LOCK_POLL_MS);+ sleepSync(RUNTIME_LOCK_POLL_MS);}}}-function releaseWindowsBinaryLock(lock) {- const owner = readBinaryLockOwner(lock.lockPath);- if (!owner || owner.token !== lock.token || owner.pid !== process.pid) {- throw new Error('Windows package-cache publication lock ownership changed');+function releaseRuntimeLock(lock) {+ try {+ assertRuntimeLockOwner(lock);+ } catch (error) {+ try { fs.closeSync(lock.fd); } catch (_) { /* already closed */ }+ throw error;}- fs.unlinkSync(path.join(lock.lockPath, 'owner.json'));- fs.rmdirSync(lock.lockPath);-}--function windowsBinaryReady(destDir, verifier = verifyCandidate) {- const binary = path.join(destDir, WINDOWS_BINARY_NAME);+ const released = `${lock.lockPath}.released-${lock.token}`;try {- const status = fs.lstatSync(binary);- if (!status.isFile() || status.isSymbolicLink()) {- return false;- }- verifier(binary);- return true;- } catch (_) {- return false;+ fs.renameSync(lock.lockPath, released);+ } catch (error) {+ fs.closeSync(lock.fd);+ throw error;+ }+ const descriptorStatus = fs.fstatSync(lock.fd, { bigint: true });+ const releasedStatus = lockPathStatus(released);+ const owner = readRuntimeLockOwner(released);+ if (!sameLockObject(descriptorStatus, releasedStatus) || !owner ||+ owner.token !== lock.token || owner.pid !== process.pid) {+ restoreDisplacedRuntimeLock(released, lock.lockPath, releasedStatus);+ fs.closeSync(lock.fd);+ throw new Error('package-cache publication lock ownership changed');+ }+ try {+ fs.unlinkSync(released);+ } finally {+ fs.closeSync(lock.fd);}}function pathMatchesDigest(candidatePath, expectedDigest) {try {const status = fs.lstatSync(candidatePath);- return status.isFile() && !status.isSymbolicLink() &&+ return status.isFile() && !status.isSymbolicLink() && status.nlink === 1 &&fileSha256(candidatePath) === expectedDigest;} catch (_) {return false;}}-function removeOwnedPublishedBinary(destDir, publishedDigests) {- for (const name of [WINDOWS_BINARY_NAME]) {- const digest = publishedDigests.get(name);+function copyRuntimeStageWithLease(source, staged, lock) {+ const input = fs.openSync(source, 'r');+ let output = null;+ const buffer = Buffer.allocUnsafe(1024 * 1024);+ let lastRefresh = Date.now();+ try {+ output = fs.openSync(staged, 'wx', 0o600);+ for (;;) {+ const count = fs.readSync(input, buffer, 0, buffer.length, null);+ if (count === 0) break;+ let offset = 0;+ while (offset < count) {+ offset += fs.writeSync(output, buffer, offset, count - offset, null);+ }+ if (Date.now() - lastRefresh >= RUNTIME_LOCK_HEARTBEAT_MS) {+ refreshRuntimeLock(lock);+ lastRefresh = Date.now();+ }+ }+ fs.fsyncSync(output);+ } catch (error) {+ try { fs.unlinkSync(staged); } catch (_) { /* never published */ }+ throw error;+ } finally {+ fs.closeSync(input);+ if (output !== null) fs.closeSync(output);+ }+}++// A grouped backup is a tiny crash journal. Before the retired marker, only+// moved members are restored; after it, partial published targets are replaced.+// cleanup-only is written only after the destination is accepted or restored,+// so a second crash can finish deletion without interpreting a partial journal.+function runtimeBackupTargetName(name, binaryName) {+ return name === binaryName || name === INTEGRATIONS_NAME ||+ (name.startsWith('cbm-ui-') && name.endsWith('.pack'));+}++function createRuntimeBackupDirectory(destDir) {+ for (let attempt = 0; attempt < 128; attempt += 1) {+ const token = crypto.randomBytes(16).toString('hex');+ const backupDir = path.join(destDir, `${RUNTIME_BACKUP_PREFIX}${token}`);+ try {+ fs.mkdirSync(backupDir, { mode: 0o700 });+ return backupDir;+ } catch (err) {+ if (!err || err.code !== 'EEXIST') throw err;+ }+ }+ throw new Error('could not reserve a package-cache backup transaction');+}++function createRuntimeBackupMarker(backupDir, markerName) {+ const marker = path.join(backupDir, markerName);+ const fd = fs.openSync(marker, 'wx', 0o600);+ try {+ fs.fsyncSync(fd);+ } finally {+ fs.closeSync(fd);+ }+}++function inspectRuntimeBackupDirectory(destDir, entryName, binaryName) {+ const backupDir = path.join(destDir, entryName);+ const directoryStatus = fs.lstatSync(backupDir);+ if (!directoryStatus.isDirectory() || directoryStatus.isSymbolicLink()) {+ throw new Error(`refusing unsafe package-cache backup: ${backupDir}`);+ }+ const backup = {+ path: backupDir,+ retired: false,+ cleanupOnly: false,+ files: new Map(),+ };+ for (const name of fs.readdirSync(backupDir).sort()) {+ const candidate = path.join(backupDir, name);+ const status = fs.lstatSync(candidate);+ if (name === RUNTIME_BACKUP_RETIRED_MARKER ||+ name === RUNTIME_BACKUP_CLEANUP_MARKER) {+ if (!status.isFile() || status.isSymbolicLink() ||+ status.nlink !== 1 || status.size !== 0) {+ throw new Error(`refusing unsafe package-cache backup marker: ${candidate}`);+ }+ if (name === RUNTIME_BACKUP_RETIRED_MARKER) backup.retired = true;+ if (name === RUNTIME_BACKUP_CLEANUP_MARKER) backup.cleanupOnly = true;+ continue;+ }+ if (!runtimeBackupTargetName(name, binaryName) ||+ !status.isFile() || status.isSymbolicLink() || status.nlink !== 1) {+ throw new Error(`refusing unsafe package-cache backup member: ${candidate}`);+ }+ backup.files.set(name, {+ path: candidate,+ digest: fileSha256(candidate),+ });+ }+ return backup;+}++function listRuntimeBackupDirectories(destDir, binaryName) {+ return fs.readdirSync(destDir)+ .filter((name) => RUNTIME_BACKUP_DIRECTORY_PATTERN.test(name))+ .sort()+ .map((name) => inspectRuntimeBackupDirectory(destDir, name, binaryName));+}++function currentRuntimeTargets(destDir, binaryName) {+ const targets = new Map();+ const names = fs.readdirSync(destDir)+ .filter((name) => runtimeBackupTargetName(name, binaryName))+ .sort();+ for (const name of names) {const target = path.join(destDir, name);- if (digest && pathMatchesDigest(target, digest)) {- try { fs.unlinkSync(target); } catch (_) { /* recovery continues below */ }+ const status = fs.lstatSync(target);+ if (!status.isFile() || status.isSymbolicLink() || status.nlink !== 1) {+ throw new Error(`refusing unsafe package-cache target: ${target}`);+ }+ targets.set(name, target);+ }+ return targets;+}++function cleanupRuntimeBackup(backup, lock) {+ assertRuntimeLockOwner(lock);+ if (!backup.cleanupOnly) {+ createRuntimeBackupMarker(backup.path, RUNTIME_BACKUP_CLEANUP_MARKER);+ backup.cleanupOnly = true;+ }+ for (const name of [...backup.files.keys()].sort()) {+ assertRuntimeLockOwner(lock);+ const member = backup.files.get(name);+ if (!member || !pathMatchesDigest(member.path, member.digest)) {+ throw new Error(`package-cache backup member changed during cleanup: ${name}`);+ }+ assertRuntimeLockOwner(lock);+ fs.unlinkSync(member.path);+ }+ if (backup.retired) {+ assertRuntimeLockOwner(lock);+ fs.unlinkSync(path.join(backup.path, RUNTIME_BACKUP_RETIRED_MARKER));+ }+ assertRuntimeLockOwner(lock);+ fs.unlinkSync(path.join(backup.path, RUNTIME_BACKUP_CLEANUP_MARKER));+ fs.rmdirSync(backup.path);+}++function copyRuntimeBackupFile(member, target, executable, lock) {+ const staged = path.join(+ path.dirname(target),+ `.cbm-runtime-recovery-${crypto.randomBytes(16).toString('hex')}`,+ );+ try {+ copyRuntimeStageWithLease(member.path, staged, lock);+ fs.chmodSync(staged, executable ? 0o755 : 0o644);+ if (fileSha256(staged) !== member.digest) {+ throw new Error('package-cache backup changed while it was being restored');}+ assertRuntimeLockOwner(lock);+ fs.renameSync(staged, target);+ } finally {+ try { fs.unlinkSync(staged); } catch (_) { /* renamed or never completed */ }}}-function restoreBinaryBackups(destDir, backups) {- for (const name of [WINDOWS_BINARY_NAME]) {- const backup = backups.get(name);+function reconcileRuntimeBackups(+ destDir, binaryName, variant, verifier, lock,+) {+ refreshRuntimeLock(lock);+ let backups = listRuntimeBackupDirectories(destDir, binaryName);+ for (const backup of backups.filter((candidate) => candidate.cleanupOnly)) {+ cleanupRuntimeBackup(backup, lock);+ }+ backups = backups.filter((candidate) => !candidate.cleanupOnly);+ if (backups.length === 0) return;++ if (runtimeSetReady(destDir, binaryName, variant, verifier)) {+ for (const backup of backups) cleanupRuntimeBackup(backup, lock);+ return;+ }+ if (backups.length === 0) return;++ for (const backup of backups.filter(+ (candidate) => !candidate.retired && candidate.files.size === 0,+ )) {+ cleanupRuntimeBackup(backup, lock);+ }+ backups = backups.filter(+ (candidate) => candidate.retired || candidate.files.size !== 0,+ );+ if (backups.length === 0) return;+ if (backups.length !== 1) {+ throw new Error('multiple package-cache backup transactions require manual recovery');+ }++ const backup = backups[0];+ const targets = currentRuntimeTargets(destDir, binaryName);+ if (!backup.retired) {+ for (const [name, member] of backup.files.entries()) {+ const target = targets.get(name);+ if (target && !pathMatchesDigest(target, member.digest)) {+ throw new Error(`package-cache backup conflicts with current target: ${name}`);+ }+ }+ } else {+ const binaryTarget = targets.get(binaryName);+ if (binaryTarget) {+ assertRuntimeLockOwner(lock);+ fs.unlinkSync(binaryTarget);+ targets.delete(binaryName);+ }+ for (const name of [...targets.keys()].sort()) {+ assertRuntimeLockOwner(lock);+ fs.unlinkSync(targets.get(name));+ targets.delete(name);+ }+ }++ const restoreNames = [...backup.files.keys()]+ .filter((name) => name !== binaryName)+ .sort();+ if (backup.files.has(binaryName)) restoreNames.push(binaryName);+ for (const name of restoreNames) {+ const member = backup.files.get(name);const target = path.join(destDir, name);- if (!backup || fs.existsSync(target)) continue;- try { fs.renameSync(backup, target); } catch (_) { /* preserve backup */ }+ if (!pathMatchesDigest(target, member.digest)) {+ copyRuntimeBackupFile(member, target, name === binaryName, lock);+ }}+ for (const [name, member] of backup.files.entries()) {+ if (!pathMatchesDigest(path.join(destDir, name), member.digest)) {+ throw new Error(`package-cache backup restoration failed: ${name}`);+ }+ }+ cleanupRuntimeBackup(backup, lock);}-function installWindowsBinaryAtomically(sourceDir, destDir, verifier = verifyCandidate) {+function publishRuntimeSetWithRecovery(+ sourceDir, destDir, binaryName, variant, verifier = verifyCandidate,+) {+ const sourceNames = runtimeSetNames(sourceDir, binaryName, variant);+ if (sourceNames === null) {+ throw new Error('source release does not contain a complete runtime set');+ }// Authenticate the source binary before it can contend for the cache.- verifier(path.join(sourceDir, WINDOWS_BINARY_NAME));- const lock = acquireWindowsBinaryLock(destDir);+ verifier(path.join(sourceDir, binaryName));+ fs.mkdirSync(destDir, { recursive: true });+ requireSafeRuntimeDirectory(destDir);+ const lock = acquireRuntimeLock(destDir);let operationError = null;try {- // A contender may have completed while this process waited. Its executable- // wins and is never moved or deleted.- if (windowsBinaryReady(destDir, verifier)) return;+ // A contender may have completed while this process waited. Its complete+ // runtime set wins and is never moved or deleted.+ refreshRuntimeLock(lock);+ reconcileRuntimeBackups(destDir, binaryName, variant, verifier, lock);+ if (runtimeSetReady(destDir, binaryName, variant, verifier)) return;- const transaction = crypto.randomBytes(16).toString('hex');+ const publicationToken = crypto.randomBytes(16).toString('hex');const stagedPaths = new Map();- const stagedDigests = new Map();- const backups = new Map();- const publishedDigests = new Map();+ let backupDirectory = null;try {- for (const name of [WINDOWS_BINARY_NAME]) {- const staged = path.join(destDir, `.cbm-pair-stage-${transaction}-${name}`);- fs.copyFileSync(path.join(sourceDir, name), staged, fs.constants.COPYFILE_EXCL);- fs.chmodSync(staged, 0o755);+ for (const name of sourceNames) {+ const staged = path.join(destDir, `.cbm-runtime-stage-${publicationToken}-${name}`);+ copyRuntimeStageWithLease(path.join(sourceDir, name), staged, lock);+ fs.chmodSync(staged, name === binaryName ? 0o755 : 0o644);stagedPaths.set(name, staged);- stagedDigests.set(name, fileSha256(staged));}+ refreshRuntimeLock(lock);+ backupDirectory = createRuntimeBackupDirectory(destDir);- for (const name of [WINDOWS_BINARY_NAME]) {+ const stalePackNames = fs.readdirSync(destDir)+ .filter((name) => name.startsWith('cbm-ui-') && name.endsWith('.pack'));+ const retireNames = [...new Set([+ binaryName,+ INTEGRATIONS_NAME,+ ...stalePackNames,+ ])];+ // Retire the binary first so an incomplete publication is never ready.+ for (const name of retireNames) {+ assertRuntimeLockOwner(lock);const target = path.join(destDir, name);const status = fs.lstatSync(target, { throwIfNoEntry: false });if (!status) continue;- if (!status.isFile() || status.isSymbolicLink()) {- throw new Error(`refusing unsafe Windows package-cache target: ${target}`);+ if (!status.isFile() || status.isSymbolicLink() || status.nlink !== 1) {+ throw new Error(`refusing unsafe package-cache target: ${target}`);}- const backup = path.join(destDir, `.cbm-pair-backup-${transaction}-${name}`);+ const backup = path.join(backupDirectory, name);fs.renameSync(target, backup);- backups.set(name, backup);}+ assertRuntimeLockOwner(lock);+ createRuntimeBackupMarker(+ backupDirectory, RUNTIME_BACKUP_RETIRED_MARKER,+ );- for (const name of [WINDOWS_BINARY_NAME]) {+ // Sidecars are committed first. The executable is the final readiness+ // signal, so no observer can accept a newly published partial set.+ for (const name of sourceNames) {+ assertRuntimeLockOwner(lock);const target = path.join(destDir, name);fs.renameSync(stagedPaths.get(name), target);stagedPaths.delete(name);- publishedDigests.set(name, stagedDigests.get(name));- }- if (!windowsBinaryReady(destDir, verifier)) {- throw new Error('published Windows package-cache binary failed verification');}- for (const backup of backups.values()) {- try { fs.unlinkSync(backup); } catch (_) { /* valid binary is already committed */ }+ if (!runtimeSetReady(destDir, binaryName, variant, verifier)) {+ throw new Error('published package-cache runtime set failed verification');}+ assertRuntimeLockOwner(lock);+ cleanupRuntimeBackup(+ inspectRuntimeBackupDirectory(+ destDir, path.basename(backupDirectory), binaryName,+ ),+ lock,+ );return;} catch (err) {- // If a non-cooperating contender nevertheless published a valid binary,- // preserve that winner. Otherwise remove only our exact staged bytes and- // restore the prior files when their target names are still absent.- if (windowsBinaryReady(destDir, verifier)) {- for (const backup of backups.values()) {- try { fs.unlinkSync(backup); } catch (_) { /* winner remains authoritative */ }+ assertRuntimeLockOwner(lock);+ const preserveWinner = runtimeSetReady(+ destDir, binaryName, variant, verifier,+ );+ if (backupDirectory !== null) {+ try {+ reconcileRuntimeBackups(+ destDir, binaryName, variant, verifier, lock,+ );+ } catch (recoveryError) {+ throw new Error(+ `${err.message}; package-cache recovery failed: ${recoveryError.message}`,+ );}- return;}- removeOwnedPublishedBinary(destDir, publishedDigests);- restoreBinaryBackups(destDir, backups);+ if (preserveWinner) return;throw err;} finally {for (const staged of stagedPaths.values()) {@@ -450,14 +919,16 @@ function installWindowsBinaryAtomically(sourceDir, destDir, verifier = verifyCanthrow err;} finally {try {- releaseWindowsBinaryLock(lock);+ releaseRuntimeLock(lock);} catch (releaseError) {if (!operationError) throw releaseError;}}}-function extractZipOnWindows(archivePath, destPath, requiredNames, extractNames) {+function extractZipOnWindows(+ archivePath, destPath, requiredNames, extractNames, ui = false,+) {// -EncodedCommand is a constant program. Paths travel only through the child// environment and are consumed with -LiteralPath, so PowerShell never parses// user/TEMP path bytes as source code or wildcard syntax.@@ -467,6 +938,8 @@ function extractZipOnWindows(archivePath, destPath, requiredNames, extractNames)'$zip = [System.IO.Compression.ZipFile]::OpenRead($env:CBM_NPM_ARCHIVE_PATH)',"$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)","$requiredNames = @($env:CBM_NPM_REQUIRED_NAMES.Split('|'))",+ "$uiRequired = $env:CBM_NPM_UI_REQUIRED -eq '1'",+ '$uiPackName = $null','$targetCounts = @{}','foreach ($requiredName in $requiredNames) { $targetCounts[$requiredName] = 0 }','try { foreach ($entry in $zip.Entries) { ' +@@ -474,23 +947,36 @@ function extractZipOnWindows(archivePath, destPath, requiredNames, extractNames)"$directory = $name.EndsWith('/'); " +"$segmentsPath = if ($directory) { $name.TrimEnd('/') } else { $name }; " +"$segments = @($segmentsPath.Split('/')); " ++ '$unixType = (($entry.ExternalAttributes -shr 16) -band 0xF000); ' +"if ([string]::IsNullOrEmpty($segmentsPath) -or $name.StartsWith('/') -or " +"$name.Contains(':') -or $segments -contains '' -or " +"$segments -contains '.' -or $segments -contains '..' -or " +- "@($segments | Where-Object { $_.EndsWith('.') -or $_.EndsWith(' ') }).Count -gt 0) { " ++ "@($segments | Where-Object { $_.EndsWith('.') -or $_.EndsWith(' ') }).Count -gt 0 -or " ++ '($unixType -ne 0 -and $unixType -ne 0x8000)) { ' +"throw \"unsafe zip entry path: $($entry.FullName)\" }; " +'if (-not $seen.Add($segmentsPath)) { ' +"throw \"duplicate or case-conflicting zip entry: $($entry.FullName)\" }; " ++ "$isUiPack = $uiRequired -and ($name -cmatch '^cbm-ui-[0-9a-f]{64}\\.pack$'); " ++ '$isRequired = $false; ' +'foreach ($requiredName in $requiredNames) { ' +'if ($name -ceq $requiredName) { ' +- '$targetCounts[$requiredName] = $targetCounts[$requiredName] + 1 } } ' ++ '$isRequired = $true; ' ++ '$targetCounts[$requiredName] = $targetCounts[$requiredName] + 1 } }; ' ++ 'if ($isUiPack) { if ($null -ne $uiPackName) { ' ++ 'throw "archive contains more than one UI pack" }; $uiPackName = $name }; ' ++ 'if ($directory -or (-not $isRequired -and -not $isUiPack)) { ' ++ 'throw "archive contains an unexpected root member: $($entry.FullName)" } ' +'} } finally { $zip.Dispose() }','foreach ($requiredName in $requiredNames) { ' +'if ($targetCounts[$requiredName] -ne 1) { ' +'throw "archive must contain exactly one $requiredName" } }',- 'if ($seen.Count -ne $requiredNames.Count) { ' ++ 'if ($uiRequired -and $null -eq $uiPackName) { ' ++ 'throw "archive must contain exactly one content-addressed UI pack" }',+ '$expectedCount = $requiredNames.Count; if ($uiRequired) { $expectedCount++ }',+ 'if ($seen.Count -ne $expectedCount) { ' +'throw "archive does not match the exact release root-file allowlist" }',"$extractNames = @($env:CBM_NPM_EXTRACT_NAMES.Split('|'))",+ 'if ($uiRequired) { $extractNames += $uiPackName }','$extractZip = [System.IO.Compression.ZipFile]::OpenRead($env:CBM_NPM_ARCHIVE_PATH)','try { foreach ($extractName in $extractNames) { ' +'$entry = @($extractZip.Entries | Where-Object { $_.FullName -ceq $extractName })[0]; ' +@@ -508,6 +994,7 @@ function extractZipOnWindows(archivePath, destPath, requiredNames, extractNames)CBM_NPM_DEST_PATH: destPath,CBM_NPM_REQUIRED_NAMES: requiredNames.join('|'),CBM_NPM_EXTRACT_NAMES: extractNames.join('|'),+ CBM_NPM_UI_REQUIRED: ui ? '1' : '0',},stdio: 'inherit',windowsHide: true,@@ -546,43 +1033,29 @@ async function main() {const platform = getPlatform();const arch = getArch();const ext = platform === 'windows' ? 'zip' : 'tar.gz';+ const selectedVariant = runtimeVariant();+ const cacheDir = cacheDirForVariant(selectedVariant);// Package-manager shims are portable one-shot instances: one cached binary// per platform, entered directly.const binName = platform === 'windows'? WINDOWS_BINARY_NAME: 'codebase-memory-mcp';- const binPath = path.join(BIN_DIR, binName);- const cacheNames = platform === 'windows'- ? [WINDOWS_BINARY_NAME]- : [binName];- const extractedNames = platform === 'windows'- ? [WINDOWS_BINARY_NAME]- : [binName];+ const extractedNames = [binName, INTEGRATIONS_NAME];const archiveNames = platform === 'windows'? WINDOWS_ARCHIVE_NAMES: UNIX_ARCHIVE_NAMES;- const cachePaths = cacheNames.map((name) => path.join(BIN_DIR, name));- if (platform === 'windows' && windowsBinaryReady(BIN_DIR)) return;- if (platform !== 'windows' &&- cachePaths.every((candidate) => fs.existsSync(candidate))) {- try {- verifyCandidate(binPath);- return; // already installed and runnable, nothing to do- } catch (_) {- // Fall through and atomically replace the invalid binary.- }- }+ if (runtimeSetReadyLocked(cacheDir, binName, selectedVariant)) return;- fs.mkdirSync(BIN_DIR, { recursive: true });+ fs.mkdirSync(cacheDir, { recursive: true });// Linux ships a fully-static "-portable" build; the standard linux binary// dynamically links glibc 2.38+ and fails on older distros. macOS/Windows// have no such variant. Keep in sync with install.sh / pypi _cli.py / cli.c.const variant = platform === 'linux' ? '-portable' : '';- // Opt into the UI build (embedded graph visualization) with CBM_VARIANT=ui.- // Default is the standard (headless) build. Mirrors install.sh --ui.- const ui = (process.env.CBM_VARIANT || '').toLowerCase() === 'ui' ? 'ui-' : '';+ // Opt into the UI build, whose verified asset pack is published beside the+ // binary, with CBM_VARIANT=ui. Default is the standard (headless) build.+ const ui = selectedVariant === 'ui' ? 'ui-' : '';const archive = `codebase-memory-mcp-${ui}${platform}-${arch}${variant}.${ext}`;const url = `https://github.com/${REPO}/releases/download/v${VERSION}/${archive}`;@@ -596,19 +1069,29 @@ async function main() {await download(url, tmpArchive);await verifyChecksum(tmpArchive, archive);- // Validate the complete archive namespace, then extract only executables.+ // Validate the complete archive namespace, then extract only the runtime set.+ let runtimeNames;if (ext === 'tar.gz') {- extractExactTarArchive(- tmpArchive, tmpDir, archiveNames, binName,+ runtimeNames = extractExactTarArchive(+ tmpArchive, tmpDir, archiveNames, extractedNames,+ selectedVariant === 'ui',);} else {- extractZipOnWindows(tmpArchive, tmpDir, archiveNames, extractedNames);+ extractZipOnWindows(+ tmpArchive, tmpDir, archiveNames, extractedNames,+ selectedVariant === 'ui',+ );+ const packNames = fs.readdirSync(tmpDir).filter((name) => UI_PACK_PATTERN.test(name));+ runtimeNames = [+ ...extractedNames,+ ...(selectedVariant === 'ui' ? packNames : []),+ ];}// Validate extracted paths don't escape tmpDir (tar-slip defense).const resolvedTmpDir = path.resolve(tmpDir);const extractedPaths = new Map();- for (const name of extractedNames) {+ for (const name of runtimeNames) {const extracted = path.join(tmpDir, name);const resolvedExtracted = path.resolve(extracted);if (!resolvedExtracted.startsWith(resolvedTmpDir + path.sep)) {@@ -616,46 +1099,22 @@ async function main() {}const status = fs.lstatSync(extracted, { throwIfNoEntry: false });if (!status || !status.isFile() || status.isSymbolicLink()) {- throw new Error(`Required binary not found as a regular file: ${extracted}`);+ throw new Error(`Required runtime member not found as a regular file: ${extracted}`);}- fs.chmodSync(extracted, 0o755);+ fs.chmodSync(extracted, name === binName ? 0o755 : 0o644);extractedPaths.set(name, extracted);}- if (platform === 'windows') {- // The launcher resolves the adjacent portable payload in this directory.- verifyCandidate(extractedPaths.get(WINDOWS_BINARY_NAME));- } else {- verifyCandidate(extractedPaths.get(binName));- }-- if (platform === 'windows') {- installWindowsBinaryAtomically(tmpDir, BIN_DIR);- } else {- const staged = path.join(- BIN_DIR,- `.${binName}.${process.pid}.${crypto.randomBytes(8).toString('hex')}.tmp`,- );- try {- fs.copyFileSync(extractedPaths.get(binName), staged, fs.constants.COPYFILE_EXCL);- fs.chmodSync(staged, 0o755);- verifyCandidate(staged);- try {- fs.renameSync(staged, binPath);- } catch (publishError) {- if (!filesEqualSha256(staged, binPath)) throw publishError;- }- verifyCandidate(binPath);- } finally {- try { fs.unlinkSync(staged); } catch (_) { /* renamed or already absent */ }- }- }+ verifyCandidate(extractedPaths.get(binName));+ publishRuntimeSetWithRecovery(+ tmpDir, cacheDir, binName, selectedVariant,+ );process.stdout.write('codebase-memory-mcp: ready.\n');if (platform === 'windows') {process.stdout.write('Windows package cache is portable. Run "codebase-memory-mcp install --yes" ' +- 'to create the managed launcher (use "npx codebase-memory-mcp install --yes" ' ++ 'to create the managed installation (use "npx codebase-memory-mcp install --yes" ' +'for a local npm install). Package updates/removal remain ' +'"npm install codebase-memory-mcp@latest" and ' +'"npm uninstall codebase-memory-mcp" (add -g for a global install).\n',@@ -675,10 +1134,21 @@ if (require.main === module || module.parent == null) {}module.exports = {+ INTEGRATIONS_NAME,UNIX_ARCHIVE_NAMES,+ UI_PACK_PATTERN,WINDOWS_BINARY_NAME,+ acquireRuntimeLock,+ cacheDirForVariant,extractExactTarArchive,- installWindowsBinaryAtomically,+ publishRuntimeSetWithRecovery,+ releaseRuntimeLock,+ refreshRuntimeLock,+ runtimeSetNames,+ runtimeSetReady,+ runtimeSetReadyLocked,+ runtimeVariant,+ tryReclaimRuntimeLock,validateExactTarMemberListing,- windowsBinaryReady,+ validateRegularTarMemberListing,};diff --git a/pkg/npm/package.json b/pkg/npm/package.jsonindex 0b076b92f..d82a14bd1 100644--- a/pkg/npm/package.json+++ b/pkg/npm/package.json@@ -1,7 +1,7 @@{"name": "codebase-memory-mcp","version": "0.8.1",- "description": "Fast code intelligence engine for AI coding agents — single static binary MCP server",+ "description": "Fast code intelligence for AI coding agents — installs a verified native runtime set","mcpName": "io.github.DeusData/codebase-memory-mcp","license": "MIT","repository": {diff --git a/pkg/npm/test/package-publication.test.js b/pkg/npm/test/package-publication.test.jsindex 560aec700..9e5849ff1 100644--- a/pkg/npm/test/package-publication.test.js+++ b/pkg/npm/test/package-publication.test.js@@ -1,17 +1,27 @@'use strict';const assert = require('node:assert/strict');+const crypto = require('node:crypto');+const { spawn } = require('node:child_process');const fs = require('node:fs');const os = require('node:os');const path = require('node:path');const test = require('node:test');const {+ INTEGRATIONS_NAME,UNIX_ARCHIVE_NAMES,WINDOWS_BINARY_NAME,+ acquireRuntimeLock,+ cacheDirForVariant,extractExactTarArchive,- installWindowsBinaryAtomically,+ publishRuntimeSetWithRecovery,+ runtimeSetReady,+ runtimeSetReadyLocked,+ releaseRuntimeLock,+ tryReclaimRuntimeLock,validateExactTarMemberListing,+ validateRegularTarMemberListing,} = require('../install.js');function exactUnixListing(extra = []) {@@ -33,28 +43,81 @@ test('Unix archive validation rejects traversal and unexpected members', () => {);});-test('Unix extraction requests only the validated root executable', () => {+test('release archives require the integrations sidecar', () => {+ assert.ok(+ UNIX_ARCHIVE_NAMES.includes(INTEGRATIONS_NAME),+ 'the authenticated archive namespace must include the runtime integrations sidecar',+ );+});++test('UI Unix archive validation accepts exactly one content-addressed pack', () => {+ const pack = `cbm-ui-${'a'.repeat(64)}.pack`;+ assert.doesNotThrow(() => validateExactTarMemberListing(+ exactUnixListing([pack]), UNIX_ARCHIVE_NAMES, true,+ ));+ assert.throws(+ () => validateExactTarMemberListing(+ exactUnixListing([pack, `cbm-ui-${'b'.repeat(64)}.pack`]),+ UNIX_ARCHIVE_NAMES,+ true,+ ),+ /exactly one|unexpected or duplicate/,+ );+});++test('Unix extraction requests only the validated runtime set', () => {const calls = [];const runner = (command, args) => {calls.push({ command, args: [...args] });- return calls.length === 1 ? exactUnixListing() : Buffer.alloc(0);+ if (args[0] === '-tzf') return exactUnixListing();+ if (args[0] === '-tvzf') {+ return UNIX_ARCHIVE_NAMES.map(+ (name) => `-rw-r--r-- 0 owner group 1 Jan 1 00:00 ${name}`,+ ).join('\n') + '\n';+ }+ return Buffer.alloc(0);};extractExactTarArchive('/tmp/release.tar.gz', '/tmp/extract', UNIX_ARCHIVE_NAMES,- 'codebase-memory-mcp', runner,+ ['codebase-memory-mcp', INTEGRATIONS_NAME], false, runner,);assert.deepEqual(calls[0].args, ['-tzf', '/tmp/release.tar.gz']);+ assert.deepEqual(calls[1].args, ['-tvzf', '/tmp/release.tar.gz']);assert.deepEqual(- calls[1].args,- ['-xzf', '/tmp/release.tar.gz', '-C', '/tmp/extract', 'codebase-memory-mcp'],+ calls[2].args,+ [+ '-xzf', '/tmp/release.tar.gz', '-C', '/tmp/extract',+ 'codebase-memory-mcp', INTEGRATIONS_NAME,+ ],);});-function writeBinary(directory, tag) {+test('Unix archive validation rejects hardlink members', () => {+ const listing = UNIX_ARCHIVE_NAMES.map(+ (name, index) => `${index === 0 ? 'h' : '-'}rw-r--r-- ${name}`,+ ).join('\n') + '\n';+ assert.throws(+ () => validateRegularTarMemberListing(listing, UNIX_ARCHIVE_NAMES.length),+ /independent regular files/,+ );+});++function writeRuntimeSet(directory, tag, variant = 'standard') {fs.mkdirSync(directory, { recursive: true });fs.writeFileSync(path.join(directory, WINDOWS_BINARY_NAME), `binary:${tag}`);+ fs.writeFileSync(path.join(directory, INTEGRATIONS_NAME), `integrations:${tag}`);+ if (variant === 'ui') {+ const contents = Buffer.from(`pack:${tag}`);+ const digest = crypto.createHash('sha256').update(contents).digest('hex');+ fs.writeFileSync(+ path.join(directory, `cbm-ui-${digest}.pack`),+ contents,+ );+ return `cbm-ui-${digest}.pack`;+ }+ return null;}function fakeBinaryVerifier(binaryPath) {@@ -81,15 +144,39 @@ function assertBinary(directory, tag) {fs.readFileSync(path.join(directory, WINDOWS_BINARY_NAME), 'utf8'),`binary:${tag}`,);+ assert.equal(+ fs.readFileSync(path.join(directory, INTEGRATIONS_NAME), 'utf8'),+ `integrations:${tag}`,+ );+}++async function waitForCrashMarker(marker, child, stderr) {+ const deadline = Date.now() + 10_000;+ while (Date.now() < deadline) {+ if (fs.existsSync(marker)) return;+ if (child.exitCode !== null || child.signalCode !== null) {+ throw new Error(`publication helper exited before crash gate: ${stderr()}`);+ }+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+ throw new Error(`publication helper did not reach crash gate: ${stderr()}`);+}++function waitForChildExit(child) {+ return new Promise((resolve) => {+ child.once('exit', (code, signal) => resolve({ code, signal }));+ });}test('Windows publication repairs a corrupt cached binary', () => {withBinaryDirectories(({ source, destination }) => {- writeBinary(source, 'candidate');- writeBinary(destination, 'old');+ writeRuntimeSet(source, 'candidate');+ writeRuntimeSet(destination, 'old');fs.writeFileSync(path.join(destination, WINDOWS_BINARY_NAME), 'corrupt');- installWindowsBinaryAtomically(source, destination, fakeBinaryVerifier);+ publishRuntimeSetWithRecovery(+ source, destination, WINDOWS_BINARY_NAME, 'standard', fakeBinaryVerifier,+ );assertBinary(destination, 'candidate');});@@ -97,9 +184,11 @@ test('Windows publication repairs a corrupt cached binary', () => {test('Windows publication installs into an empty cache', () => {withBinaryDirectories(({ source, destination }) => {- writeBinary(source, 'candidate');+ writeRuntimeSet(source, 'candidate');- installWindowsBinaryAtomically(source, destination, fakeBinaryVerifier);+ publishRuntimeSetWithRecovery(+ source, destination, WINDOWS_BINARY_NAME, 'standard', fakeBinaryVerifier,+ );assertBinary(destination, 'candidate');});@@ -107,11 +196,334 @@ test('Windows publication installs into an empty cache', () => {test('Windows publication preserves a valid concurrent winner', () => {withBinaryDirectories(({ source, destination }) => {- writeBinary(source, 'loser');- writeBinary(destination, 'winner');+ writeRuntimeSet(source, 'loser');+ writeRuntimeSet(destination, 'winner');- installWindowsBinaryAtomically(source, destination, fakeBinaryVerifier);+ publishRuntimeSetWithRecovery(+ source, destination, WINDOWS_BINARY_NAME, 'standard', fakeBinaryVerifier,+ );assertBinary(destination, 'winner');});});++test('runtime readiness requires the complete variant-specific set', () => {+ withBinaryDirectories(({ destination }) => {+ writeRuntimeSet(destination, 'standard');+ assert.equal(+ runtimeSetReady(destination, WINDOWS_BINARY_NAME, 'standard', fakeBinaryVerifier),+ true,+ );+ fs.unlinkSync(path.join(destination, INTEGRATIONS_NAME));+ assert.equal(+ runtimeSetReady(destination, WINDOWS_BINARY_NAME, 'standard', fakeBinaryVerifier),+ false,+ );++ writeRuntimeSet(destination, 'ui', 'ui');+ assert.equal(+ runtimeSetReady(destination, WINDOWS_BINARY_NAME, 'ui', fakeBinaryVerifier),+ true,+ );+ fs.writeFileSync(+ path.join(destination, `cbm-ui-${'b'.repeat(64)}.pack`),+ 'second pack',+ );+ assert.equal(+ runtimeSetReady(destination, WINDOWS_BINARY_NAME, 'ui', fakeBinaryVerifier),+ false,+ );+ });+});++test('UI readiness rejects and publication repairs a digest-mismatched pack', () => {+ withBinaryDirectories(({ source, destination }) => {+ const sourcePack = writeRuntimeSet(source, 'candidate', 'ui');+ const corruptPack = writeRuntimeSet(destination, 'old', 'ui');+ fs.writeFileSync(path.join(destination, corruptPack), 'corrupt pack bytes');++ assert.equal(+ runtimeSetReady(destination, WINDOWS_BINARY_NAME, 'ui', fakeBinaryVerifier),+ false,+ 'a well-shaped pack filename must not authenticate different bytes',+ );+ publishRuntimeSetWithRecovery(+ source, destination, WINDOWS_BINARY_NAME, 'ui', fakeBinaryVerifier,+ );++ assertBinary(destination, 'candidate');+ assert.equal(fs.readFileSync(path.join(destination, sourcePack), 'utf8'), 'pack:candidate');+ assert.equal(fs.existsSync(path.join(destination, corruptPack)), false);+ });+});++test('standard and UI cache directories do not collide', () => {+ assert.notEqual(cacheDirForVariant('standard'), cacheDirForVariant('ui'));+});++test('runtime publication commits sidecars before the binary', () => {+ withBinaryDirectories(({ source, destination }) => {+ writeRuntimeSet(source, 'candidate', 'ui');+ const committed = [];+ const renameSync = fs.renameSync;+ fs.renameSync = (sourcePath, destinationPath) => {+ const name = path.basename(destinationPath);+ if (path.dirname(destinationPath) === destination &&+ (name === WINDOWS_BINARY_NAME || name === INTEGRATIONS_NAME ||+ /^cbm-ui-[0-9a-f]{64}\.pack$/.test(name))) {+ committed.push(name);+ }+ return renameSync(sourcePath, destinationPath);+ };+ try {+ publishRuntimeSetWithRecovery(+ source, destination, WINDOWS_BINARY_NAME, 'ui', fakeBinaryVerifier,+ );+ } finally {+ fs.renameSync = renameSync;+ }++ assert.equal(committed[0], INTEGRATIONS_NAME);+ assert.match(committed[1], /^cbm-ui-[0-9a-f]{64}\.pack$/);+ assert.equal(committed[2], WINDOWS_BINARY_NAME);+ });+});++test('a killed publisher is reconciled on the next locked readiness check', async () => {+ const helperSource = String.raw`+ 'use strict';+ const fs = require('node:fs');+ const path = require('node:path');+ const [installPath, source, destination, marker, crashName] = process.argv.slice(1);+ const install = require(installPath);+ const renameSync = fs.renameSync;+ fs.renameSync = (sourcePath, destinationPath) => {+ const result = renameSync(sourcePath, destinationPath);+ if (destinationPath === path.join(destination, crashName)) {+ fs.writeFileSync(marker, 'reached\n');+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 60_000);+ }+ return result;+ };+ const verifier = (binaryPath) => {+ if (!/^binary:(.+)$/.test(fs.readFileSync(binaryPath, 'utf8'))) {+ throw new Error('test binary failed verification');+ }+ };+ install.publishRuntimeSetWithRecovery(+ source, destination, install.WINDOWS_BINARY_NAME, 'standard', verifier,+ );+ `;++ for (const [crashName, expectedReady] of [+ [INTEGRATIONS_NAME, false],+ [WINDOWS_BINARY_NAME, true],+ ]) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cbm-npm-crash-test-'));+ const source = path.join(root, 'source');+ const destination = path.join(root, 'destination');+ const marker = path.join(root, 'crash-reached');+ fs.mkdirSync(destination);+ writeRuntimeSet(source, 'candidate');+ writeRuntimeSet(destination, 'old');+ fs.writeFileSync(+ path.join(destination, WINDOWS_BINARY_NAME), 'corrupt:old',+ );+ let stderr = '';+ const child = spawn(process.execPath, [+ '-e',+ helperSource,+ path.join(__dirname, '..', 'install.js'),+ source,+ destination,+ marker,+ crashName,+ ], { stdio: ['ignore', 'ignore', 'pipe'] });+ child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });+ const exitPromise = waitForChildExit(child);+ try {+ await waitForCrashMarker(marker, child, () => stderr);+ const backups = fs.readdirSync(destination)+ .filter((name) => name.startsWith('.cbm-runtime-backup-'));+ assert.equal(backups.length, 1, 'killed publisher did not retain one transaction');+ assert.equal(+ fs.lstatSync(path.join(destination, backups[0])).isDirectory(),+ true,+ );+ assert.equal(+ fs.existsSync(path.join(+ destination, backups[0], '.retirement-complete',+ )),+ true,+ );++ assert.equal(child.kill('SIGKILL'), true);+ const exit = await exitPromise;+ assert.ok(+ exit.signal !== null || exit.code !== 0,+ 'publication helper was not killed',+ );++ const ready = runtimeSetReadyLocked(+ destination,+ WINDOWS_BINARY_NAME,+ 'standard',+ fakeBinaryVerifier,+ );+ assert.equal(ready, expectedReady);+ if (!ready) {+ assert.equal(+ fs.readFileSync(path.join(destination, WINDOWS_BINARY_NAME), 'utf8'),+ 'corrupt:old',+ );+ assert.equal(+ fs.readFileSync(path.join(destination, INTEGRATIONS_NAME), 'utf8'),+ 'integrations:old',+ );+ publishRuntimeSetWithRecovery(+ source,+ destination,+ WINDOWS_BINARY_NAME,+ 'standard',+ fakeBinaryVerifier,+ );+ }+ assertBinary(destination, 'candidate');+ assert.equal(+ fs.readdirSync(destination).some(+ (name) => name.startsWith('.cbm-runtime-backup-'),+ ),+ false,+ );+ assert.equal(+ fs.existsSync(path.join(destination, '.codebase-memory-mcp-runtime.lock')),+ false,+ );+ } finally {+ if (child.exitCode === null && child.signalCode === null) {+ child.kill('SIGKILL');+ await exitPromise;+ }+ fs.rmSync(root, { recursive: true, force: true });+ }+ }+});++test('a stalled creator never deletes a successor runtime lock', () => {+ withBinaryDirectories(({ destination }) => {+ let successor;+ let injected = false;+ assert.throws(+ () => acquireRuntimeLock(destination, () => {+ if (injected) return;+ injected = true;+ successor = acquireRuntimeLock(destination);+ throw new Error('injected stalled creator abort');+ }),+ /injected stalled creator abort/,+ );++ assert.ok(successor, 'the successor must acquire the reclaimed lock');+ assert.ok(+ fs.existsSync(successor.lockPath),+ 'the failed creator must not recursively remove its successor',+ );+ releaseRuntimeLock(successor);+ });+});++test('runtime readiness rejects multiply-linked cache leaves', () => {+ withBinaryDirectories(({ destination }) => {+ writeRuntimeSet(destination, 'linked');+ fs.linkSync(+ path.join(destination, INTEGRATIONS_NAME),+ path.join(destination, 'integrations-hardlink'),+ );+ assert.equal(+ runtimeSetReady(destination, WINDOWS_BINARY_NAME, 'standard', fakeBinaryVerifier),+ false,+ );+ });+});++test('orphan reconciliation rejects multiply-linked backup members', () => {+ withBinaryDirectories(({ destination }) => {+ const backup = path.join(+ destination, `.cbm-runtime-backup-${'a'.repeat(32)}`,+ );+ fs.mkdirSync(backup);+ fs.writeFileSync(path.join(backup, '.retirement-complete'), '');+ const member = path.join(backup, WINDOWS_BINARY_NAME);+ fs.writeFileSync(member, 'binary:old');+ fs.linkSync(member, path.join(destination, 'backup-hardlink-copy'));++ assert.throws(+ () => runtimeSetReadyLocked(+ destination,+ WINDOWS_BINARY_NAME,+ 'standard',+ fakeBinaryVerifier,+ ),+ /unsafe package-cache backup member/,+ );+ assert.equal(fs.existsSync(backup), true, 'unsafe backup was mutated');+ assert.equal(+ fs.existsSync(path.join(destination, '.codebase-memory-mcp-runtime.lock')),+ false,+ );+ });+});++test('an expired lease never reclaims a live owner', () => {+ withBinaryDirectories(({ destination }) => {+ const lockPath = path.join(destination, '.codebase-memory-mcp-runtime.lock');+ const owner = {+ pid: process.pid,+ token: 'a'.repeat(32),+ lease_expires_ms: Date.now() - 1,+ };+ const ownerRecord = `${JSON.stringify(owner)}\n`;+ fs.writeFileSync(lockPath, ownerRecord);+ const before = fs.lstatSync(lockPath, { bigint: true });++ assert.equal(tryReclaimRuntimeLock(lockPath, 'b'.repeat(32)), false);+ const after = fs.lstatSync(lockPath, { bigint: true });+ assert.equal(fs.readFileSync(lockPath, 'utf8'), ownerRecord);+ assert.equal(JSON.parse(fs.readFileSync(lockPath, 'utf8')).token, owner.token);+ assert.equal(after.dev, before.dev);+ assert.equal(after.ino, before.ino);+ });+});++test('a stale legacy lock never reclaims a live owner', () => {+ withBinaryDirectories(({ destination }) => {+ const lockPath = path.join(destination, '.codebase-memory-mcp-runtime.lock');+ const ownerRecord = `${JSON.stringify({+ pid: process.pid,+ token: 'a'.repeat(32),+ })}\n`;+ fs.mkdirSync(lockPath);+ fs.writeFileSync(path.join(lockPath, 'owner.json'), ownerRecord);+ const stale = new Date(Date.now() - 3_600_001);+ fs.utimesSync(lockPath, stale, stale);+ const before = fs.lstatSync(lockPath, { bigint: true });++ assert.equal(tryReclaimRuntimeLock(lockPath, 'b'.repeat(32)), false);+ const after = fs.lstatSync(lockPath, { bigint: true });+ assert.equal(fs.readFileSync(path.join(lockPath, 'owner.json'), 'utf8'), ownerRecord);+ assert.equal(after.dev, before.dev);+ assert.equal(after.ino, before.ino);+ });+});++test('a stale ownerless lock is reclaimed', () => {+ withBinaryDirectories(({ destination }) => {+ const lockPath = path.join(destination, '.codebase-memory-mcp-runtime.lock');+ fs.writeFileSync(lockPath, '');+ const stale = new Date(Date.now() - 30_001);+ fs.utimesSync(lockPath, stale, stale);++ assert.equal(tryReclaimRuntimeLock(lockPath, 'b'.repeat(32)), true);+ assert.equal(fs.existsSync(lockPath), false);+ });+});diff --git a/pkg/npm/test/windows-launcher.test.js b/pkg/npm/test/windows-launcher.test.jsindex 756b238cb..da19f459b 100644--- a/pkg/npm/test/windows-launcher.test.js+++ b/pkg/npm/test/windows-launcher.test.js@@ -1,11 +1,15 @@'use strict';const assert = require('node:assert/strict');+const crypto = require('node:crypto');const fs = require('node:fs');const path = require('node:path');const test = require('node:test');const vm = require('node:vm');+const UI_PACK_BYTES = Buffer.from('authenticated UI pack');+const UI_PACK_NAME = `cbm-ui-${crypto.createHash('sha256').update(UI_PACK_BYTES).digest('hex')}.pack`;+class ExitSignal extends Error {constructor(code) {super(`process.exit(${code})`);@@ -13,26 +17,77 @@ class ExitSignal extends Error {}}-function runShim(targetPlatform, arguments_, childStatus) {+function runShim(targetPlatform, arguments_, childStatus, options = {}) {const shimPath = path.join(__dirname, '..', 'bin.js');const source = fs.readFileSync(shimPath, 'utf8').replace(/^#![^\n]*\n/, '');const calls = [];+ const lockEvents = [];let stderr = '';+ let installed = false;const fakeProcess = {platform: targetPlatform,+ env: {+ CBM_VARIANT: options.variant || '',+ LOCALAPPDATA: 'C:\\Users\\test\\AppData\\Local',+ },argv: ['node.exe', shimPath, ...arguments_],execPath: 'node.exe',stderr: { write: (text) => { stderr += String(text); } },exit: (code) => { throw new ExitSignal(code); },};const fakeFs = {- existsSync: () => true,+ lstatSync: (candidate) => {+ if (options.missingSidecar && !installed &&+ path.basename(candidate) === 'cbm-integrations.json') {+ const error = new Error('missing sidecar');+ error.code = 'ENOENT';+ throw error;+ }+ return { isFile: () => true, isSymbolicLink: () => false, nlink: 1 };+ },+ readFileSync: () => options.corruptPack && !installed+ ? Buffer.from('corrupt UI pack')+ : UI_PACK_BYTES,+ readdirSync: () => options.variant === 'ui'+ ? [UI_PACK_NAME]+ : [],};const fakeChildProcess = {+ spawn: (executable, args, options) => {+ calls.push({ executable, args, options });+ return {+ on: (event, callback) => {+ if (event === 'close') callback(childStatus);+ return this;+ },+ };+ },spawnSync: (executable, args, options) => {calls.push({ executable, args, options });- return { status: calls.length === 1 ? 0 : childStatus };+ if (executable === fakeProcess.execPath) {+ installed = true;+ return { status: 0 };+ }+ if (args[0] === '--verify-runtime-assets') return { status: 0 };+ return { status: childStatus };+ },+ };+ const fakeLifecycle = {+ acquireRuntimeLock: () => {+ lockEvents.push('acquire');+ return { lockPath: 'lock', token: 'token', fd: 1 };+ },+ refreshRuntimeLock: () => { lockEvents.push('refresh'); },+ releaseRuntimeLock: () => { lockEvents.push('release'); },+ runtimeSetReady: () => true,+ runtimeSetReadyLocked: (directory, binaryName) => {+ const structurallyReady = installed || (!options.missingSidecar && !options.corruptPack);+ if (!structurallyReady) return false;+ const probe = fakeChildProcess.spawnSync(+ path.join(directory, binaryName), ['--verify-runtime-assets'], { stdio: 'ignore' },+ );+ return probe.status === 0;},};const sandbox = {@@ -47,8 +102,11 @@ function runShim(targetPlatform, arguments_, childStatus) {require: (specifier) => {if (specifier === 'fs') return fakeFs;if (specifier === 'child_process') return fakeChildProcess;+ if (specifier === './install.js') return fakeLifecycle;return require(specifier);},+ clearInterval: () => {},+ setInterval: () => 1,setTimeout,};@@ -59,10 +117,10 @@ function runShim(targetPlatform, arguments_, childStatus) {if (!(error instanceof ExitSignal)) throw error;exitCode = error.code;}- return { calls, exitCode, stderr };+ return { calls, exitCode, lockEvents, stderr };}-test('Windows npm shim probes and executes the cached launcher', () => {+test('Windows npm shim authenticates assets and executes the cached binary', () => {const observed = runShim('win32', ['--version'], 0);assert.equal(observed.exitCode, 0);@@ -74,25 +132,82 @@ test('Windows npm shim probes and executes the cached launcher', () => {'codebase-memory-mcp.payload.exe',);}+ assert.deepEqual(Array.from(observed.calls[0].args), ['--verify-runtime-assets']);assert.deepEqual(Array.from(observed.calls[1].args), ['--version']);assert.equal(observed.calls[1].options.stdio, 'inherit');});-test('Windows npm shim keeps package-manager guidance after launcher refusal', () => {+test('npm update is routed to the package manager without invoking absent install.sh', () => {const observed = runShim('win32', ['update'], 1);- assert.equal(observed.exitCode, 1);- assert.equal(path.basename(observed.calls[1].executable), 'codebase-memory-mcp.exe');+ assert.equal(observed.exitCode, 2);+ assert.equal(observed.calls.length, 0, 'update guidance must not launch cached code');assert.match(observed.stderr, /npm install codebase-memory-mcp@latest/);- assert.match(observed.stderr, /install --yes/);+ assert.match(observed.stderr, /codebase-memory-mcp install --yes/);+ assert.doesNotMatch(observed.stderr, /install\.sh/);});-test('non-Windows npm shim keeps its native payload execution path', () => {+test('nested update token is forwarded instead of treated as package update', () => {+ const observed = runShim('win32', ['daemon', 'update'], 0);++ assert.equal(observed.exitCode, 0);+ assert.equal(observed.calls.length, 2);+ assert.deepEqual(Array.from(observed.calls[1].args), ['daemon', 'update']);+ assert.doesNotMatch(observed.stderr, /npm install codebase-memory-mcp@latest/);+});++test('non-Windows npm shim executes its cached binary directly', () => {const observed = runShim('darwin', ['--version'], 0);assert.equal(observed.exitCode, 0);- assert.equal(observed.calls.length, 1);- assert.equal(path.basename(observed.calls[0].executable), 'codebase-memory-mcp');+ assert.equal(observed.calls.length, 2);+ assert.deepEqual(Array.from(observed.calls[0].args), ['--verify-runtime-assets']);+ assert.equal(path.basename(observed.calls[1].executable), 'codebase-memory-mcp');+});++test('npm shim selects a separate UI runtime set', () => {+ const observed = runShim('darwin', ['--version'], 0, { variant: 'ui' });++ assert.equal(observed.exitCode, 0);+ assert.equal(path.basename(path.dirname(observed.calls[1].executable)), 'ui');+});++test('npm shim repairs a cache whose integrations sidecar is missing', () => {+ const observed = runShim(+ 'darwin', ['--version'], 0, { missingSidecar: true },+ );++ assert.equal(observed.exitCode, 0);+ assert.equal(observed.calls[0].executable, 'node.exe');+ assert.equal(path.basename(observed.calls[0].args[0]), 'install.js');+ assert.deepEqual(Array.from(observed.calls[1].args), ['--verify-runtime-assets']);+ assert.equal(path.basename(observed.calls[2].executable), 'codebase-memory-mcp');+});++test('npm shim repairs a UI cache whose pack digest does not match its name', () => {+ const observed = runShim(+ 'darwin', ['--version'], 0, { variant: 'ui', corruptPack: true },+ );++ assert.equal(observed.exitCode, 0);+ assert.equal(observed.calls[0].executable, 'node.exe');+ assert.equal(path.basename(observed.calls[0].args[0]), 'install.js');+ assert.deepEqual(Array.from(observed.calls[1].args), ['--verify-runtime-assets']);+ assert.equal(path.basename(observed.calls[2].executable), 'codebase-memory-mcp');+});++test('wrapper uninstall locks the cache and targets the managed install by default', () => {+ const observed = runShim('win32', ['uninstall', '--yes'], 0);++ assert.equal(observed.exitCode, 0);+ assert.deepEqual(observed.lockEvents, ['acquire', 'refresh', 'release']);+ assert.deepEqual(+ Array.from(observed.calls[1].args),+ [+ 'uninstall', '--yes', '--dir',+ 'C:\\Users\\test\\AppData\\Local/Programs/codebase-memory-mcp',+ ],+ );});test('PowerShell install mutation runs through the downloaded binary', () => {@@ -111,8 +226,12 @@ test('PowerShell install mutation runs through the downloaded binary', () => {);// One binary ships per platform — no launcher/payload pair to resolve.assert.doesNotMatch(installer, /payload/i);- // A running .exe cannot be overwritten, so an in-place update has to retire- // the existing binary by renaming it aside first. This script IS the Windows- // update path, so losing that step would silently break every update.- assert.match(installer, /Move-Item[\s\S]{0,80}\$Dest[\s\S]{0,40}\$retired/);+ // The candidate owns activation and rollback under the native guard. The+ // script must not mutate the installed binary before handing it the request.+ const handoff = installer.indexOf('& $DownloadedBinary @InstallArgs');+ assert.ok(handoff > 0, 'downloaded candidate handoff is missing');+ assert.doesNotMatch(+ installer.slice(0, handoff),+ /(?:Move-Item|Copy-Item|Remove-Item)[^\n]*(?:\$Dest|\$InstallDir[^\n]*\$BinName)/,+ );});diff --git a/pkg/pypi/README.md b/pkg/pypi/README.mdindex 97d09ccaf..f75af8715 100644--- a/pkg/pypi/README.md+++ b/pkg/pypi/README.md@@ -4,7 +4,7 @@ mcp-name: io.github.DeusData/codebase-memory-mcp**Fast code intelligence engine for AI coding agents.** Indexes an average repository in milliseconds, the Linux kernel (28M LOC) in 3 minutes. Answers structural queries in under 1ms.-This package installs the `codebase-memory-mcp` binary from [GitHub Releases](https://github.com/DeusData/codebase-memory-mcp/releases). The binary is downloaded on first run and cached in your OS cache directory.+This Python wrapper downloads the selected `codebase-memory-mcp` runtime set from [GitHub Releases](https://github.com/DeusData/codebase-memory-mcp/releases) on first run and verifies it before publishing it in your OS cache directory. The standard set contains the native executable and authenticated integration asset; `CBM_VARIANT=ui` additionally selects the content-addressed UI pack.## Installation@@ -14,6 +14,8 @@ pip install codebase-memory-mcppipx install codebase-memory-mcp```+To use the UI variant, set `CBM_VARIANT=ui` when invoking the wrapper (and consistently for any package-managed update or reinstall).+## Usage```bash@@ -27,7 +29,7 @@ codebase-memory-mcp --help|---------|-------------|| macOS | arm64, amd64 || Linux | arm64, amd64 |-| Windows | amd64 |+| Windows | arm64, amd64 |## Full documentationdiff --git a/pkg/pypi/pyproject.toml b/pkg/pypi/pyproject.tomlindex 9a430644a..18807810d 100644--- a/pkg/pypi/pyproject.toml+++ b/pkg/pypi/pyproject.toml@@ -5,7 +5,7 @@ build-backend = "hatchling.build"[project]name = "codebase-memory-mcp"version = "0.8.1"-description = "Fast code intelligence engine for AI coding agents — single static binary MCP server"+description = "Fast code intelligence for AI coding agents — installs a verified native runtime set"readme = "README.md"license = { text = "MIT" }requires-python = ">=3.8"diff --git a/pkg/pypi/src/codebase_memory_mcp/_cli.py b/pkg/pypi/src/codebase_memory_mcp/_cli.pyindex 473c2d026..05f854e6f 100644--- a/pkg/pypi/src/codebase_memory_mcp/_cli.py+++ b/pkg/pypi/src/codebase_memory_mcp/_cli.py@@ -1,13 +1,18 @@"""Downloads codebase-memory-mcp on first run, then runs its native entry point."""+import errnoimport hashlib+import jsonimport osimport platform+import re+import secretsimport shutilimport statimport subprocessimport sysimport tempfile+import threadingimport timeimport urllib.errorimport urllib.parse@@ -16,8 +21,18 @@ from pathlib import PathREPO = "DeusData/codebase-memory-mcp"_WINDOWS_BINARY_NAME = "codebase-memory-mcp.exe"+_INTEGRATIONS_NAME = "cbm-integrations.json"+_UI_PACK_RE = re.compile(r"cbm-ui-[0-9a-f]{64}\.pack\Z")+_UNIX_ARCHIVE_NAMES = (+ "codebase-memory-mcp",+ _INTEGRATIONS_NAME,+ "LICENSE",+ "install.sh",+ "THIRD_PARTY_NOTICES.md",+)_WINDOWS_ARCHIVE_NAMES = (_WINDOWS_BINARY_NAME,+ _INTEGRATIONS_NAME,"LICENSE","install.ps1","THIRD_PARTY_NOTICES.md",@@ -32,6 +47,18 @@ _NETWORK_TIMEOUT_SECONDS = 120_CANDIDATE_TIMEOUT_SECONDS = 15_MAX_CHECKSUM_MANIFEST_BYTES = 1024 * 1024_REDIRECT_CODES = frozenset({301, 302, 303, 307, 308})+_RUNTIME_LOCK_NAME = ".codebase-memory-mcp-runtime.lock"+_RUNTIME_LOCK_WAIT_SECONDS = 45+_RUNTIME_OWNERLESS_STALE_SECONDS = 30+_RUNTIME_LOCK_POLL_SECONDS = 0.025+_RUNTIME_LOCK_LEASE_SECONDS = 300+_RUNTIME_LOCK_HEARTBEAT_SECONDS = 20+_RUNTIME_LEGACY_STALE_SECONDS = 3600+_RUNTIME_BACKUP_PREFIX = ".cbm-runtime-backup-"+_RUNTIME_BACKUP_RE = re.compile(r"\.cbm-runtime-backup-[0-9a-f]{32}\Z")+_RUNTIME_BACKUP_RETIRED_MARKER = ".retirement-complete"+_RUNTIME_BACKUP_CLEANUP_MARKER = ".cleanup-only"+_runtime_lock_claim_observer = Noneclass _NoRedirectHandler(urllib.request.HTTPRedirectHandler):@@ -111,7 +138,7 @@ def _verify_candidate(path: Path) -> None:"""Require a staged native candidate to execute successfully."""try:subprocess.run(- [str(path), "--version"],+ [str(path), "--verify-runtime-assets"],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,@@ -133,8 +160,8 @@ def _file_sha256(path: Path) -> str:def _files_equal_sha256(left: Path, right: Path) -> bool:try:return (- left.is_file()- and right.is_file()+ _regular_file(left)+ and _regular_file(right)and left.stat().st_size == right.stat().st_sizeand _file_sha256(left) == _file_sha256(right))@@ -142,34 +169,77 @@ def _files_equal_sha256(left: Path, right: Path) -> bool:return False-def _safe_extract_tar(tf, dest: str) -> None:- """Extract a tarfile to dest, rejecting path-traversal entries.-- Uses the tarfile data filter on Python >=3.12 (PEP 706), falls back to- manual per-member path validation on older Pythons. Mitigates the- classic tar-slip / Zip Slip vulnerability (CWE-22).- """- if hasattr(tf, "extraction_filter") or sys.version_info >= (3, 12):- tf.extractall(dest, filter="data")- return-- dest_abs = os.path.abspath(dest)- for member in tf.getmembers():- if member.issym() or member.islnk():+def _validate_archive_names(names, archive_names, ui: bool, casefold: bool = False):+ """Require the exact release root namespace and return its UI pack name."""+ required = tuple(archive_names)+ required_set = set(required)+ found = set()+ seen = set()+ ui_pack = None+ for name in names:+ key = name.casefold() if casefold else name+ if key in seen:sys.exit(- f"codebase-memory-mcp: refusing unsafe tar entry "- f"(link: {member.name!r})"+ f"codebase-memory-mcp: refusing unsafe archive entry "+ f"(duplicate or case conflict: {name!r})")- member_abs = os.path.abspath(os.path.join(dest_abs, member.name))- if not (member_abs == dest_abs or member_abs.startswith(dest_abs + os.sep)):+ seen.add(key)+ is_ui_pack = ui and _UI_PACK_RE.fullmatch(name) is not None+ if name not in required_set and not is_ui_pack:+ sys.exit(+ f"codebase-memory-mcp: archive must contain only the exact "+ f"root files: {', '.join(required)}"+ )+ if is_ui_pack:+ if ui_pack is not None:+ sys.exit(+ "codebase-memory-mcp: archive must contain exactly one "+ "content-addressed UI pack"+ )+ ui_pack = name+ else:+ found.add(name)+ expected_count = len(required) + (1 if ui else 0)+ if found != required_set or len(seen) != expected_count or (ui and ui_pack is None):+ sys.exit(+ f"codebase-memory-mcp: archive must contain exactly one of each "+ f"required root file: {', '.join(required)}"+ )+ return ui_pack+++def _safe_extract_tar(+ tf, dest: str, archive_names=(), extract_names=(), ui: bool = False+):+ """Validate a tar namespace, then extract only its authenticated runtime set."""+ members = tf.getmembers()+ for member in members:+ if not member.isfile():sys.exit(f"codebase-memory-mcp: refusing unsafe tar entry "- f"(escapes dest: {member.name!r})"+ f"(not a regular root file: {member.name!r})")- tf.extractall(dest)+ ui_pack = _validate_archive_names(+ [member.name for member in members], archive_names, ui+ )+ runtime_names = list(extract_names)+ if ui_pack is not None:+ runtime_names.append(ui_pack)+ by_name = {member.name: member for member in members}+ dest_abs = os.path.abspath(dest)+ for name in runtime_names:+ source = tf.extractfile(by_name[name])+ if source is None:+ sys.exit(f"codebase-memory-mcp: could not read archive member: {name}")+ target = os.path.join(dest_abs, name)+ with source, open(target, "xb") as output:+ shutil.copyfileobj(source, output)+ return tuple(runtime_names)-def _safe_extract_zip(zf, dest: str, archive_names=(), extract_names=()) -> None:+def _safe_extract_zip(+ zf, dest: str, archive_names=(), extract_names=(), ui: bool = False+):"""Extract a zipfile after validating its Windows-style namespace.Windows treats paths case-insensitively. Rejecting duplicate/case-conflicting@@ -177,10 +247,7 @@ def _safe_extract_zip(zf, dest: str, archive_names=(), extract_names=()) -> Nonethat a portable package-manager shim eventually executes."""dest_abs = os.path.abspath(dest)- seen = set()- required = tuple(archive_names)- required_set = set(required)- found = set()+ names = []for info in zf.infolist():raw_name = info.filenamename = raw_name.replace("\\", "/")@@ -197,38 +264,31 @@ def _safe_extract_zip(zf, dest: str, archive_names=(), extract_names=()) -> Nonef"codebase-memory-mcp: refusing unsafe zip entry "f"(invalid path: {raw_name!r})")- folded = segments_name.casefold()- if folded in seen:+ unix_type = stat.S_IFMT((info.external_attr >> 16) & 0xFFFF)+ if info.is_dir() or unix_type not in (0, stat.S_IFREG):sys.exit(f"codebase-memory-mcp: refusing unsafe zip entry "- f"(duplicate or case conflict: {raw_name!r})"+ f"(not a regular root file: {raw_name!r})")- seen.add(folded)- if name not in required_set or info.is_dir():- sys.exit(- f"codebase-memory-mcp: archive must contain only the exact "- f"root files: {', '.join(required)}"- )- found.add(name)+ names.append(name)member_abs = os.path.abspath(os.path.join(dest_abs, *segments))if not (member_abs == dest_abs or member_abs.startswith(dest_abs + os.sep)):sys.exit(f"codebase-memory-mcp: refusing unsafe zip entry "f"(escapes dest: {raw_name!r})")- missing = required_set - found- if missing or len(seen) != len(required):- sys.exit(- f"codebase-memory-mcp: archive must contain exactly one of each "- f"required root file: {', '.join(required)}"- )+ ui_pack = _validate_archive_names(names, archive_names, ui, casefold=True)- # Extract only the two validated executable files. This avoids relying on+ # Extract only the validated runtime files. This avoids relying on# platform-specific zip path rewriting and always creates regular files.- for name in extract_names:+ runtime_names = list(extract_names)+ if ui_pack is not None:+ runtime_names.append(ui_pack)+ for name in runtime_names:target = os.path.join(dest_abs, name)with zf.open(name) as source, open(target, "xb") as output:shutil.copyfileobj(source, output)+ return tuple(runtime_names)def _verify_checksum(archive_path: str, archive_name: str, version: str) -> None:@@ -329,14 +389,22 @@ def _cache_dir() -> Path:return base / "codebase-memory-mcp"-def _bin_path(version: str) -> Path:+def _variant() -> str:+ return "ui" if os.environ.get("CBM_VARIANT", "").lower() == "ui" else "standard"+++def _runtime_dir(version: str, variant: str = None) -> Path:+ return _cache_dir() / version / (variant or _variant())+++def _bin_path(version: str, variant: str = None) -> Path:# One binary per platform: the cached file is the executed file.name = (_WINDOWS_BINARY_NAMEif sys.platform == "win32"else "codebase-memory-mcp")- return _cache_dir() / version / name+ return _runtime_dir(version, variant) / namedef _execution_path(binary: Path, target_platform: str) -> Path:@@ -344,33 +412,777 @@ def _execution_path(binary: Path, target_platform: str) -> Path:return binary-def _windows_binary_ready(version: str) -> bool:- binary = _cache_dir() / version / _WINDOWS_BINARY_NAME- if not binary.is_file():+def _regular_file(path: Path) -> bool:+ try:+ status = path.lstat()+ return (+ stat.S_ISREG(status.st_mode)+ and not stat.S_ISLNK(status.st_mode)+ and status.st_nlink == 1+ )+ except OSError:+ return False+++def _ui_pack_path_matches_name(path: Path, name: str) -> bool:+ try:+ expected = name[len("cbm-ui-") : -len(".pack")]+ return _file_sha256(path) == expected+ except OSError:return False+++def _ui_pack_matches_digest(path: Path) -> bool:+ return _ui_pack_path_matches_name(path, path.name)+++def _runtime_set_names(directory: Path, binary_name: str, variant: str):+ if not _regular_file(directory / binary_name) or not _regular_file(+ directory / _INTEGRATIONS_NAME+ ):+ return None+ try:+ pack_like = [+ path+ for path in directory.iterdir()+ if path.name.startswith("cbm-ui-") and path.name.endswith(".pack")+ ]+ except OSError:+ return None+ valid_packs = [+ path+ for path in pack_like+ if _UI_PACK_RE.fullmatch(path.name) is not None+ and _regular_file(path)+ and _ui_pack_matches_digest(path)+ ]+ if variant == "ui":+ if len(pack_like) != 1 or len(valid_packs) != 1:+ return None+ elif pack_like:+ return None+ return (+ _INTEGRATIONS_NAME,+ *((valid_packs[0].name,) if variant == "ui" else ()),+ binary_name,+ )+++def _runtime_set_ready(version: str, verifier=None) -> bool:+ variant = _variant()+ binary = _bin_path(version, variant)+ if _runtime_set_names(binary.parent, binary.name, variant) is None:+ return False+ if verifier is not None:+ try:+ verifier(binary)+ except RuntimeError:+ return False+ return True+++def _require_safe_runtime_directory(directory: Path):+ status = directory.lstat()+ if not stat.S_ISDIR(status.st_mode) or stat.S_ISLNK(status.st_mode):+ raise RuntimeError(f"refusing unsafe package-cache directory: {directory}")+++def _runtime_set_ready_locked(version: str) -> bool:+ binary = _bin_path(version)+ binary.parent.mkdir(parents=True, exist_ok=True)+ _require_safe_runtime_directory(binary.parent)+ lock, _ = _acquire_runtime_lock(binary.parent)+ try:+ _refresh_runtime_lock(lock)+ _reconcile_runtime_backups(+ binary.parent, binary.name, _variant(), _verify_candidate, lock+ )+ return _runtime_set_ready(version, _verify_candidate)+ finally:+ _release_runtime_lock(lock)+++def _runtime_set_fingerprint(directory: Path, binary_name: str, variant: str):+ """Identify one complete set so a lock waiter can preserve its winner."""+ names = _runtime_set_names(directory, binary_name, variant)+ if names is None:+ return None+ try:+ return tuple(+ (name, _file_sha256(directory / name)) for name in names+ )+ except OSError:+ return None+++def _staged_runtime_names(staged_paths, binary_name: str, variant: str):+ names = set(staged_paths)+ required = {binary_name, _INTEGRATIONS_NAME}+ pack_names = [+ name+ for name in names+ if name.startswith("cbm-ui-") and name.endswith(".pack")+ ]+ if variant == "ui":+ if len(pack_names) != 1 or _UI_PACK_RE.fullmatch(pack_names[0]) is None:+ raise RuntimeError("staged UI runtime set must contain exactly one pack")+ pack_name = pack_names[0]+ if not _regular_file(staged_paths[pack_name]) or not _ui_pack_path_matches_name(+ staged_paths[pack_name], pack_name+ ):+ raise RuntimeError("staged UI pack digest does not match its filename")+ required.add(pack_name)+ runtime_names = (_INTEGRATIONS_NAME, pack_name, binary_name)+ else:+ if pack_names:+ raise RuntimeError("standard runtime set must not contain a UI pack")+ runtime_names = (_INTEGRATIONS_NAME, binary_name)+ if names != required or any(+ not _regular_file(staged_paths[name]) for name in required+ ):+ raise RuntimeError("staged package cache is incomplete")+ return runtime_names+++def _process_is_alive(pid: int) -> bool:+ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:+ return False+ try:+ os.kill(pid, 0)+ return True+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ except OSError as exc:+ return exc.errno != errno.ESRCH+++def _runtime_lock_status(lock_path: Path):+ try:+ return lock_path.lstat()+ except OSError:+ return None+++def _same_runtime_lock_object(left, right):+ return (+ left is not None+ and right is not None+ and left.st_dev == right.st_dev+ and left.st_ino == right.st_ino+ and stat.S_IFMT(left.st_mode) == stat.S_IFMT(right.st_mode)+ )+++def _read_runtime_lock_owner(lock_path: Path):+ try:+ status = lock_path.lstat()+ if stat.S_ISLNK(status.st_mode) or not (+ stat.S_ISREG(status.st_mode) or stat.S_ISDIR(status.st_mode)+ ):+ return None+ owner_path = lock_path / "owner.json" if stat.S_ISDIR(status.st_mode) else lock_path+ owner = json.loads(owner_path.read_text(encoding="utf-8"))+ except (OSError, ValueError, TypeError):+ return None+ pid = owner.get("pid")+ token = owner.get("token")+ if (+ not isinstance(pid, int)+ or isinstance(pid, bool)+ or pid <= 0+ or not isinstance(token, str)+ or re.fullmatch(r"[0-9a-f]{32}", token) is None+ ):+ return None+ lease_expires = owner.get("lease_expires_ms")+ if not isinstance(lease_expires, (int, float)) or isinstance(+ lease_expires, bool+ ):+ lease_expires = None+ return pid, token, lease_expires+++def _restore_displaced_runtime_lock(reclaimed: Path, lock_path: Path, status):+ if status is None or not stat.S_ISREG(status.st_mode):+ return+ try:+ os.link(reclaimed, lock_path)+ reclaimed.unlink()+ except OSError:+ # A newer owner holds the canonical name. Preserve the displaced lock;+ # never delete a lock whose identity was not the one inspected.+ pass+++def _try_reclaim_runtime_lock(lock_path: Path, contender_token: str):+ """Return whether to retry now and whether a contender released the lock."""+ observed_status = _runtime_lock_status(lock_path)+ if observed_status is None:+ return True, True+ if stat.S_ISLNK(observed_status.st_mode) or not (+ stat.S_ISREG(observed_status.st_mode)+ or stat.S_ISDIR(observed_status.st_mode)+ ):+ return False, False+ owner = _read_runtime_lock_owner(lock_path)+ reclaim = owner is not None and not _process_is_alive(owner[0])+ if owner is None:+ reclaim = (+ time.time() - observed_status.st_mtime+ >= _RUNTIME_OWNERLESS_STALE_SECONDS+ )+ if not reclaim:+ return False, False+ reclaimed = lock_path.with_name(+ f"{lock_path.name}.reclaimed-{contender_token}"+ )+ try:+ os.rename(lock_path, reclaimed)+ except FileNotFoundError:+ return True, True+ except OSError:+ return False, False+ moved_status = _runtime_lock_status(reclaimed)+ if not _same_runtime_lock_object(observed_status, moved_status):+ _restore_displaced_runtime_lock(reclaimed, lock_path, moved_status)+ return False, False+ moved_owner = _read_runtime_lock_owner(reclaimed)+ still_reclaimable = (+ time.time() - moved_status.st_mtime >= _RUNTIME_OWNERLESS_STALE_SECONDS+ if moved_owner is None+ else not _process_is_alive(moved_owner[0])+ )+ if not still_reclaimable:+ _restore_displaced_runtime_lock(reclaimed, lock_path, moved_status)+ return False, False+ if stat.S_ISDIR(moved_status.st_mode):+ shutil.rmtree(reclaimed)+ else:+ reclaimed.unlink()+ return True, False+++def _write_runtime_lock_owner(owner_fd: int, token: str):+ record = (+ json.dumps(+ {+ "pid": os.getpid(),+ "token": token,+ "lease_expires_ms": int(+ (time.time() + _RUNTIME_LOCK_LEASE_SECONDS) * 1000+ ),+ },+ separators=(",", ":"),+ )+ + "\n"+ ).encode()+ os.ftruncate(owner_fd, 0)+ os.lseek(owner_fd, 0, os.SEEK_SET)+ offset = 0+ while offset < len(record):+ offset += os.write(owner_fd, record[offset:])+ os.fsync(owner_fd)+++def _assert_runtime_lock_owner(lock):+ lock_path, token, owner_fd = lock+ descriptor_status = os.fstat(owner_fd)+ canonical_status = _runtime_lock_status(lock_path)+ owner = _read_runtime_lock_owner(lock_path)+ if (+ not _same_runtime_lock_object(descriptor_status, canonical_status)+ or owner is None+ or owner[:2] != (os.getpid(), token)+ ):+ raise RuntimeError("package-cache publication lock ownership changed")+++def _refresh_runtime_lock(lock):+ _assert_runtime_lock_owner(lock)+ _write_runtime_lock_owner(lock[2], lock[1])+ _assert_runtime_lock_owner(lock)+++def _acquire_runtime_lock(directory: Path):+ token = secrets.token_hex(16)+ lock_path = directory / _RUNTIME_LOCK_NAME+ claim_path = lock_path.with_name(f"{lock_path.name}.claim-{token}")+ deadline = time.monotonic() + _RUNTIME_LOCK_WAIT_SECONDS+ contended = False+ while True:+ owner_fd = None+ try:+ owner_fd = os.open(+ claim_path,+ os.O_RDWR | os.O_CREAT | os.O_EXCL,+ 0o600,+ )+ try:+ _write_runtime_lock_owner(owner_fd, token)+ if _runtime_lock_claim_observer is not None:+ _runtime_lock_claim_observer()+ os.link(claim_path, lock_path)+ claim_path.unlink()+ if not _same_runtime_lock_object(+ os.fstat(owner_fd), _runtime_lock_status(lock_path)+ ):+ raise RuntimeError(+ "package-cache publication lock ownership changed"+ )+ except BaseException:+ os.close(owner_fd)+ owner_fd = None+ try:+ claim_path.unlink()+ except OSError:+ pass+ raise+ return (lock_path, token, owner_fd), contended+ except FileExistsError:+ retry, released_by_contender = _try_reclaim_runtime_lock(+ lock_path, token+ )+ contended = contended or released_by_contender+ if retry:+ continue+ contended = True+ if time.monotonic() >= deadline:+ raise RuntimeError(+ "timed out waiting for package-cache publication lock"+ )+ time.sleep(_RUNTIME_LOCK_POLL_SECONDS)+++def _release_runtime_lock(lock):+ lock_path, token, owner_fd = lock+ try:+ _assert_runtime_lock_owner(lock)+ except Exception:+ os.close(owner_fd)+ raise+ released = lock_path.with_name(f"{lock_path.name}.released-{token}")+ try:+ os.rename(lock_path, released)+ except Exception:+ os.close(owner_fd)+ raise+ descriptor_status = os.fstat(owner_fd)+ released_status = _runtime_lock_status(released)+ owner = _read_runtime_lock_owner(released)+ if (+ not _same_runtime_lock_object(descriptor_status, released_status)+ or owner is None+ or owner[:2] != (os.getpid(), token)+ ):+ _restore_displaced_runtime_lock(released, lock_path, released_status)+ os.close(owner_fd)+ raise RuntimeError("package-cache publication lock ownership changed")+ try:+ released.unlink()+ finally:+ os.close(owner_fd)+++# A grouped backup is a small crash journal. The retired marker separates a+# partial retirement from partial publication; cleanup-only makes deletion+# retryable after the destination has been accepted or restored.+def _runtime_backup_target_name(name: str, binary_name: str) -> bool:+ return (+ name == binary_name+ or name == _INTEGRATIONS_NAME+ or (name.startswith("cbm-ui-") and name.endswith(".pack"))+ )+++def _create_runtime_backup_directory(directory: Path) -> Path:+ for _ in range(128):+ backup = directory / f"{_RUNTIME_BACKUP_PREFIX}{secrets.token_hex(16)}"+ try:+ backup.mkdir(mode=0o700)+ return backup+ except FileExistsError:+ continue+ raise RuntimeError("could not reserve a package-cache backup transaction")+++def _create_runtime_backup_marker(backup: Path, name: str):+ descriptor = os.open(backup / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)try:- _verify_candidate(binary)- except RuntimeError:+ os.fsync(descriptor)+ finally:+ os.close(descriptor)+++def _inspect_runtime_backup(directory: Path, entry_name: str, binary_name: str):+ backup_path = directory / entry_name+ try:+ directory_status = backup_path.lstat()+ except OSError as exc:+ raise RuntimeError(+ f"refusing unsafe package-cache backup: {backup_path}"+ ) from exc+ if not stat.S_ISDIR(directory_status.st_mode) or stat.S_ISLNK(+ directory_status.st_mode+ ):+ raise RuntimeError(f"refusing unsafe package-cache backup: {backup_path}")+ backup = {+ "path": backup_path,+ "retired": False,+ "cleanup_only": False,+ "files": {},+ }+ for candidate in sorted(backup_path.iterdir(), key=lambda path: path.name):+ status = candidate.lstat()+ if candidate.name in (+ _RUNTIME_BACKUP_RETIRED_MARKER,+ _RUNTIME_BACKUP_CLEANUP_MARKER,+ ):+ if (+ not stat.S_ISREG(status.st_mode)+ or stat.S_ISLNK(status.st_mode)+ or status.st_nlink != 1+ or status.st_size != 0+ ):+ raise RuntimeError(+ f"refusing unsafe package-cache backup marker: {candidate}"+ )+ if candidate.name == _RUNTIME_BACKUP_RETIRED_MARKER:+ backup["retired"] = True+ else:+ backup["cleanup_only"] = True+ continue+ if (+ not _runtime_backup_target_name(candidate.name, binary_name)+ or not stat.S_ISREG(status.st_mode)+ or stat.S_ISLNK(status.st_mode)+ or status.st_nlink != 1+ ):+ raise RuntimeError(+ f"refusing unsafe package-cache backup member: {candidate}"+ )+ backup["files"][candidate.name] = (candidate, _file_sha256(candidate))+ return backup+++def _list_runtime_backups(directory: Path, binary_name: str):+ names = sorted(+ path.name+ for path in directory.iterdir()+ if _RUNTIME_BACKUP_RE.fullmatch(path.name) is not None+ )+ return [+ _inspect_runtime_backup(directory, name, binary_name) for name in names+ ]+++def _current_runtime_targets(directory: Path, binary_name: str):+ targets = {}+ for target in sorted(directory.iterdir(), key=lambda path: path.name):+ if not _runtime_backup_target_name(target.name, binary_name):+ continue+ status = target.lstat()+ if (+ not stat.S_ISREG(status.st_mode)+ or stat.S_ISLNK(status.st_mode)+ or status.st_nlink != 1+ ):+ raise RuntimeError(f"refusing unsafe package-cache target: {target}")+ targets[target.name] = target+ return targets+++def _runtime_set_ready_at(+ directory: Path, binary_name: str, variant: str, verifier=None+) -> bool:+ if _runtime_set_names(directory, binary_name, variant) is None:return False+ if verifier is not None:+ try:+ verifier(directory / binary_name)+ except (OSError, RuntimeError):+ return Falsereturn True+def _cleanup_runtime_backup(backup, lock):+ _assert_runtime_lock_owner(lock)+ if not backup["cleanup_only"]:+ _create_runtime_backup_marker(+ backup["path"], _RUNTIME_BACKUP_CLEANUP_MARKER+ )+ backup["cleanup_only"] = True+ for name in sorted(backup["files"]):+ _assert_runtime_lock_owner(lock)+ member, digest = backup["files"][name]+ if not _path_matches_digest(member, digest):+ raise RuntimeError(+ f"package-cache backup member changed during cleanup: {name}"+ )+ _assert_runtime_lock_owner(lock)+ member.unlink()+ if backup["retired"]:+ _assert_runtime_lock_owner(lock)+ (backup["path"] / _RUNTIME_BACKUP_RETIRED_MARKER).unlink()+ _assert_runtime_lock_owner(lock)+ (backup["path"] / _RUNTIME_BACKUP_CLEANUP_MARKER).unlink()+ backup["path"].rmdir()+++def _copy_runtime_backup_file(+ member: Path, target: Path, expected_digest: str, executable: bool, lock+):+ descriptor, staged_name = tempfile.mkstemp(+ dir=str(target.parent), prefix=".cbm-runtime-recovery-"+ )+ staged = Path(staged_name)+ last_refresh = time.monotonic()+ try:+ with member.open("rb") as source, os.fdopen(descriptor, "wb") as output:+ descriptor = None+ while True:+ block = source.read(1024 * 1024)+ if not block:+ break+ output.write(block)+ if time.monotonic() - last_refresh >= _RUNTIME_LOCK_HEARTBEAT_SECONDS:+ _refresh_runtime_lock(lock)+ last_refresh = time.monotonic()+ output.flush()+ os.fsync(output.fileno())+ staged.chmod(0o755 if executable else 0o644)+ if _file_sha256(staged) != expected_digest:+ raise RuntimeError(+ "package-cache backup changed while it was being restored"+ )+ _assert_runtime_lock_owner(lock)+ os.replace(staged, target)+ finally:+ if descriptor is not None:+ os.close(descriptor)+ try:+ staged.unlink()+ except FileNotFoundError:+ pass+++def _reconcile_runtime_backups(+ directory: Path, binary_name: str, variant: str, verifier, lock+):+ _refresh_runtime_lock(lock)+ backups = _list_runtime_backups(directory, binary_name)+ for backup in [item for item in backups if item["cleanup_only"]]:+ _cleanup_runtime_backup(backup, lock)+ backups = [item for item in backups if not item["cleanup_only"]]+ if not backups:+ return++ if _runtime_set_ready_at(directory, binary_name, variant, verifier):+ for backup in backups:+ _cleanup_runtime_backup(backup, lock)+ return+ if not backups:+ return++ for backup in [+ item+ for item in backups+ if not item["retired"] and not item["files"]+ ]:+ _cleanup_runtime_backup(backup, lock)+ backups = [+ item for item in backups if item["retired"] or item["files"]+ ]+ if not backups:+ return+ if len(backups) != 1:+ raise RuntimeError(+ "multiple package-cache backup transactions require manual recovery"+ )++ backup = backups[0]+ targets = _current_runtime_targets(directory, binary_name)+ if not backup["retired"]:+ for name, (_, digest) in backup["files"].items():+ target = targets.get(name)+ if target is not None and not _path_matches_digest(target, digest):+ raise RuntimeError(+ f"package-cache backup conflicts with current target: {name}"+ )+ else:+ binary_target = targets.pop(binary_name, None)+ if binary_target is not None:+ _assert_runtime_lock_owner(lock)+ binary_target.unlink()+ for name in sorted(targets):+ _assert_runtime_lock_owner(lock)+ targets[name].unlink()++ restore_names = sorted(+ name for name in backup["files"] if name != binary_name+ )+ if binary_name in backup["files"]:+ restore_names.append(binary_name)+ for name in restore_names:+ member, digest = backup["files"][name]+ target = directory / name+ if not _path_matches_digest(target, digest):+ _copy_runtime_backup_file(+ member, target, digest, name == binary_name, lock+ )+ for name, (_, digest) in backup["files"].items():+ if not _path_matches_digest(directory / name, digest):+ raise RuntimeError(+ f"package-cache backup restoration failed: {name}"+ )+ _cleanup_runtime_backup(backup, lock)+++def _path_matches_digest(path: Path, expected: str) -> bool:+ try:+ return _regular_file(path) and _file_sha256(path) == expected+ except OSError:+ return False+++def _publish_runtime_set(+ staged_paths,+ dest: Path,+ binary_name: str,+ variant: str,+ replace_file=None,+ verifier=None,+):+ """Publish sidecars first, retaining exact-byte backups for recovery."""+ runtime_names = _staged_runtime_names(staged_paths, binary_name, variant)+ if replace_file is None:+ replace_file = os.replace+ _require_safe_runtime_directory(dest.parent)+ initial_fingerprint = _runtime_set_fingerprint(+ dest.parent, binary_name, variant+ )+ lock, contended = _acquire_runtime_lock(dest.parent)+ operation_error = None+ try:+ _refresh_runtime_lock(lock)+ _reconcile_runtime_backups(+ dest.parent, binary_name, variant, verifier, lock+ )+ # Preserve a complete set that appeared or changed while this publisher+ # waited. An unchanged pre-existing set may still be repaired/replaced,+ # with its bytes retained below for rollback.+ locked_fingerprint = _runtime_set_fingerprint(+ dest.parent, binary_name, variant+ )+ if (+ locked_fingerprint is not None+ and (contended or locked_fingerprint != initial_fingerprint)+ ):+ return++ backup_directory = None+ try:+ backup_directory = _create_runtime_backup_directory(dest.parent)+ pack_like = sorted(+ path.name+ for path in dest.parent.iterdir()+ if path.name.startswith("cbm-ui-")+ and path.name.endswith(".pack")+ )+ retire_names = (binary_name, _INTEGRATIONS_NAME, *pack_like)+ retired = set()+ # Retire the executable first: until the final rename, readiness is false.+ for name in retire_names:+ _assert_runtime_lock_owner(lock)+ if name in retired:+ continue+ retired.add(name)+ target = dest.parent / name+ try:+ status = target.lstat()+ except FileNotFoundError:+ continue+ if (+ not stat.S_ISREG(status.st_mode)+ or stat.S_ISLNK(status.st_mode)+ or status.st_nlink != 1+ ):+ raise RuntimeError(+ f"refusing unsafe package-cache target: {target}"+ )+ replace_file(target, backup_directory / name)+ _assert_runtime_lock_owner(lock)+ _create_runtime_backup_marker(+ backup_directory, _RUNTIME_BACKUP_RETIRED_MARKER+ )++ for name in runtime_names:+ _assert_runtime_lock_owner(lock)+ target = dest.parent / name+ try:+ replace_file(staged_paths[name], target)+ staged_paths.pop(name)+ except OSError as publish_error:+ if not _files_equal_sha256(staged_paths[name], target):+ raise publish_error+ if _runtime_set_names(dest.parent, binary_name, variant) is None:+ raise RuntimeError("published package cache is incomplete")+ if verifier is not None:+ verifier(dest.parent / binary_name)+ _assert_runtime_lock_owner(lock)+ except Exception as publication_error:+ _assert_runtime_lock_owner(lock)+ # Preserve a complete non-cooperating winner; never delete its bytes.+ preserve_winner = _runtime_set_ready_at(+ dest.parent, binary_name, variant, verifier+ )+ if backup_directory is not None:+ try:+ _reconcile_runtime_backups(+ dest.parent, binary_name, variant, verifier, lock+ )+ except Exception as recovery_error:+ raise RuntimeError(+ f"{publication_error}; package-cache recovery failed: "+ f"{recovery_error}"+ ) from recovery_error+ if preserve_winner:+ return+ raise+ else:+ backup = _inspect_runtime_backup(+ dest.parent, backup_directory.name, binary_name+ )+ _cleanup_runtime_backup(backup, lock)+ except Exception as exc:+ operation_error = exc+ raise+ finally:+ try:+ _release_runtime_lock(lock)+ except Exception:+ if operation_error is None:+ raise++def _download(version: str) -> Path:os_name = _os_name()arch = _arch()ext = "zip" if os_name == "windows" else "tar.gz"+ selected_variant = _variant()# Linux ships a fully-static "-portable" build; the standard linux binary# dynamically links glibc 2.38+ and fails on older distros. macOS/Windows# have no such variant. Keep in sync with install.sh / install.js / cli.c.- variant = "-portable" if os_name == "linux" else ""- # Opt into the UI build (embedded graph visualization) with CBM_VARIANT=ui.- # Default is the standard (headless) build. Mirrors install.sh --ui.- ui = "ui-" if os.environ.get("CBM_VARIANT", "").lower() == "ui" else ""- archive = f"codebase-memory-mcp-{ui}{os_name}-{arch}{variant}.{ext}"+ portable = "-portable" if os_name == "linux" else ""+ # Opt into the UI build, whose verified asset pack is published beside the+ # binary, with CBM_VARIANT=ui. Default is the standard (headless) build.+ ui = "ui-" if selected_variant == "ui" else ""+ archive = f"codebase-memory-mcp-{ui}{os_name}-{arch}{portable}.{ext}"url = f"https://github.com/{REPO}/releases/download/v{version}/{archive}"_validate_url_scheme(url)- dest = _bin_path(version)+ dest = _bin_path(version, selected_variant)dest.parent.mkdir(parents=True, exist_ok=True)print(@@ -394,45 +1206,65 @@ def _download(version: str) -> Path:bin_name = (_WINDOWS_BINARY_NAME if os_name == "windows" else "codebase-memory-mcp")- extraction_names = (bin_name,)- cache_names = extraction_names- publish_names = cache_names+ extraction_names = (bin_name, _INTEGRATIONS_NAME)+ archive_names = (+ _WINDOWS_ARCHIVE_NAMES+ if os_name == "windows"+ else _UNIX_ARCHIVE_NAMES+ )if ext == "tar.gz":import tarfilewith tarfile.open(tmp_archive) as tf:- _safe_extract_tar(tf, tmp)+ runtime_names = _safe_extract_tar(+ tf,+ tmp,+ archive_names,+ extraction_names,+ selected_variant == "ui",+ )else:import zipfilewith zipfile.ZipFile(tmp_archive) as zf:- _safe_extract_zip(+ runtime_names = _safe_extract_zip(zf,tmp,- _WINDOWS_ARCHIVE_NAMES,+ archive_names,extraction_names,+ selected_variant == "ui",)extracted_paths = {}- for name in extraction_names:+ for name in runtime_names:extracted_path = Path(tmp) / name- if not extracted_path.is_file():+ if not _regular_file(extracted_path):sys.exit(- f"codebase-memory-mcp: required binary not found after "+ f"codebase-memory-mcp: required runtime member not found after "f"extraction: {name}")- current = extracted_path.stat().st_mode- extracted_path.chmod(- current | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH- )+ if name == bin_name:+ current = extracted_path.stat().st_mode+ extracted_path.chmod(+ current | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH+ )extracted_paths[name] = extracted_path+ if _runtime_set_names(Path(tmp), bin_name, selected_variant) is None:+ sys.exit(+ "codebase-memory-mcp: extracted runtime set failed content "+ "verification"+ )try:_verify_candidate(extracted_paths[bin_name])- except RuntimeError as exc:+ except (OSError, RuntimeError) as exc:sys.exit(f"codebase-memory-mcp: {exc}")staged_paths = {}try:- for name in cache_names:- staged_suffix = ".tmp.exe" if sys.platform == "win32" else ".tmp"+ for name in runtime_names:+ staged_suffix = (+ ".tmp.exe"+ if sys.platform == "win32" and name == bin_name+ else ".tmp"+ )with tempfile.NamedTemporaryFile(dir=str(dest.parent),prefix=f".{name}.",@@ -441,31 +1273,24 @@ def _download(version: str) -> Path:) as staged:staged_path = Path(staged.name)shutil.copy2(extracted_paths[name], staged_path)- staged_mode = staged_path.stat().st_mode- staged_path.chmod(- staged_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH- )+ if name == bin_name:+ staged_mode = staged_path.stat().st_mode+ staged_path.chmod(+ staged_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH+ )staged_paths[name] = staged_path- if os_name != "windows":- _verify_candidate(staged_paths[bin_name])- for name in publish_names:- target = dest.parent / name- try:- os.replace(staged_paths[name], target)- staged_paths.pop(name)- except OSError as publish_error:- # Never unlink a destination here: it may belong to a- # concurrent contender. A collision remains eligible only- # when its bytes match this authenticated stage; pair- # execution is checked after payload is published last.- if not _files_equal_sha256(staged_paths[name], target):- raise publish_error- if os_name == "windows":- _verify_candidate(dest.parent / _WINDOWS_BINARY_NAME)- else:- _verify_candidate(dest)- except RuntimeError as exc:+ # A crash during publication leaves an incomplete cache, which+ # readiness rejects and the next invocation repairs.+ _publish_runtime_set(+ staged_paths,+ dest,+ bin_name,+ selected_variant,+ verifier=_verify_candidate,+ )+ _verify_candidate(dest)+ except (OSError, RuntimeError) as exc:sys.exit(f"codebase-memory-mcp: {exc}")finally:for staged_path in staged_paths.values():@@ -480,12 +1305,18 @@ def _download(version: str) -> Path:def main() -> None:version = _version()bin_path = _bin_path(version)+ mutation = _runtime_mutation_action(sys.argv[1:])+ if mutation == "update":+ print(+ "This PyPI copy is maintained by pip. Update it with "+ '"python -m pip install --upgrade codebase-memory-mcp". '+ "For a managed standalone installation, run "+ '"codebase-memory-mcp install --yes".',+ file=sys.stderr,+ )+ raise SystemExit(2)- cache_ready = (- _windows_binary_ready(version)- if sys.platform == "win32"- else bin_path.is_file()- )+ cache_ready = _runtime_set_ready_locked(version)if not cache_ready:bin_path = _download(version)@@ -495,41 +1326,101 @@ def main() -> None:# element as a discrete argv entry — no shell interpretation, no# injection vector. sys.argv forwarding is the whole point of this# shim, so tainted-input suppression is intentional.- args = [str(execution_path)] + sys.argv[1:]+ forwarded = _native_args(sys.argv[1:])+ args = [str(execution_path)] + forwarded++ if mutation in ("install", "uninstall"):+ result = _run_cache_sensitive_mutation(version, execution_path, forwarded)+ if sys.platform == "win32" and result != 0 and mutation == "uninstall":+ print(+ 'This PyPI Windows copy is portable. Use '+ '"python -m pip uninstall codebase-memory-mcp" for package maintenance. '+ "To create or repair a managed standalone installation, run "+ '"codebase-memory-mcp install --yes".',+ file=sys.stderr,+ )+ raise SystemExit(result)if sys.platform != "win32":os.execv(str(execution_path), args) # noqa: S606 — list form, no shellelse:result = subprocess.run(args) # noqa: S603 — list form, no shell=True- mutation = _portable_mutation_action(sys.argv[1:])- if result.returncode != 0 and mutation is not None:- package_command = (- "python -m pip install --upgrade codebase-memory-mcp"- if mutation == "update"- else "python -m pip uninstall codebase-memory-mcp"- )- print(- f'This PyPI Windows copy is portable. Use "{package_command}" '- f'for package maintenance, or run "codebase-memory-mcp '- f'install --yes" once to create a managed launcher with '- f'coordinated self-update/uninstall.',- file=sys.stderr,- )sys.exit(result.returncode)-def _portable_mutation_action(args):+def _runtime_mutation_action(args):for argument in args:- if argument in (- "cli",- "hook-augment",- "config",- "install",- "--help",- "-h",- "--version",- ):+ if argument in ("--help", "-h", "--version"):return None- if argument in ("update", "uninstall"):+ if argument.startswith("-"):+ continue+ if argument in ("install", "update", "uninstall"):return argument+ if argument in ("cli", "hook-augment", "config"):+ return None+ return Nonereturn None+++def _default_managed_install_dir() -> Path:+ if sys.platform != "win32":+ return Path.home() / ".local" / "bin"+ local_app_data = Path(+ os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")+ )+ return local_app_data / "Programs" / "codebase-memory-mcp"+++def _native_args(args):+ result = list(args)+ if _runtime_mutation_action(result) == "uninstall" and not any(+ argument == "--dir" or argument.startswith("--dir=")+ for argument in result+ ):+ result.extend(("--dir", str(_default_managed_install_dir())))+ return result+++def _run_cache_sensitive_mutation(version: str, executable: Path, args) -> int:+ directory = executable.parent+ _require_safe_runtime_directory(directory)+ lock, _ = _acquire_runtime_lock(directory)+ stop = threading.Event()+ heartbeat_errors = []++ def heartbeat():+ while not stop.wait(_RUNTIME_LOCK_HEARTBEAT_SECONDS):+ try:+ _refresh_runtime_lock(lock)+ except Exception as exc: # surfaced on the launcher thread+ heartbeat_errors.append(exc)+ return++ try:+ _refresh_runtime_lock(lock)+ if not _runtime_set_ready(version, _verify_candidate):+ raise RuntimeError(+ "cached runtime assets changed before mutation launch"+ )+ thread = threading.Thread(+ name="cbm-cache-lock-heartbeat", target=heartbeat, daemon=True+ )+ thread.start()+ process = subprocess.Popen( # noqa: S603 — argv list, no shell+ [str(executable), *args]+ )+ while process.poll() is None:+ if heartbeat_errors:+ process.terminate()+ process.wait()+ raise RuntimeError(+ f"package-cache lock lost during mutation: "+ f"{heartbeat_errors[0]}"+ )+ time.sleep(0.05)+ return process.returncode+ finally:+ stop.set()+ if "thread" in locals():+ thread.join(timeout=1)+ _release_runtime_lock(lock)diff --git a/pkg/pypi/tests/test_cli.py b/pkg/pypi/tests/test_cli.pyindex 4fe297689..8590280b2 100644--- a/pkg/pypi/tests/test_cli.py+++ b/pkg/pypi/tests/test_cli.py@@ -1,6 +1,17 @@+import hashlib+import json+import os+import stat+import subprocessimport sys+import tarfile+import tempfile+import threading+import timeimport unittest+import zipfilefrom pathlib import Path+from unittest import mockPACKAGE_ROOT = Path(__file__).resolve().parents[1]@@ -22,14 +33,811 @@ class BinarySelectionTests(unittest.TestCase):self.assertEqual(_cli._execution_path(binary, "linux"), binary)- def test_portable_mutation_guidance_classification_is_preserved(self):- self.assertEqual(_cli._portable_mutation_action(["update"]), "update")+ def test_cache_sensitive_mutation_classification_is_explicit(self):+ self.assertEqual(_cli._runtime_mutation_action(["update"]), "update")self.assertEqual(- _cli._portable_mutation_action(["uninstall", "--yes"]),+ _cli._runtime_mutation_action(["uninstall", "--yes"]),"uninstall",)- self.assertIsNone(_cli._portable_mutation_action(["install", "--yes"]))- self.assertIsNone(_cli._portable_mutation_action(["cli", "update"]))+ self.assertEqual(+ _cli._runtime_mutation_action(["install", "--yes"]), "install"+ )+ self.assertIsNone(_cli._runtime_mutation_action(["cli", "update"]))+ self.assertIsNone(_cli._runtime_mutation_action(["daemon", "update"]))++ def test_wrapper_uninstall_never_defaults_to_its_cache_binary(self):+ with mock.patch.object(Path, "home", return_value=Path("/home/user")):+ self.assertEqual(+ _cli._native_args(["uninstall", "--yes"]),+ ["uninstall", "--yes", "--dir", "/home/user/.local/bin"],+ )+ self.assertEqual(+ _cli._native_args(["uninstall", "--dir", "/custom/bin"]),+ ["uninstall", "--dir", "/custom/bin"],+ )++ def test_standard_and_ui_cache_paths_do_not_collide(self):+ with mock.patch.dict("os.environ", {"CBM_VARIANT": "standard"}):+ standard = _cli._bin_path("0.8.1")+ with mock.patch.dict("os.environ", {"CBM_VARIANT": "ui"}):+ ui = _cli._bin_path("0.8.1")++ self.assertNotEqual(standard, ui)++ def test_release_archives_require_the_integrations_sidecar(self):+ self.assertIn("cbm-integrations.json", _cli._WINDOWS_ARCHIVE_NAMES)++ def test_update_guidance_uses_pip_and_names_managed_install(self):+ with mock.patch.object(_cli.sys, "argv", ["cbm", "update"]), \+ mock.patch.object(_cli, "_version", return_value="0.8.1"), \+ mock.patch("sys.stderr") as stderr:+ with self.assertRaisesRegex(SystemExit, "2"):+ _cli.main()++ output = "".join(call.args[0] for call in stderr.write.call_args_list)+ self.assertIn(+ "python -m pip install --upgrade codebase-memory-mcp", output+ )+ self.assertIn("codebase-memory-mcp install --yes", output)+ self.assertNotIn("install.sh", output)+++class RuntimeSetTests(unittest.TestCase):+ def test_candidate_probe_authenticates_adjacent_runtime_assets(self):+ with mock.patch.object(_cli.subprocess, "run") as run:+ run.return_value.returncode = 0+ _cli._verify_candidate(Path("/tmp/codebase-memory-mcp"))++ self.assertEqual(+ run.call_args.args[0],+ ["/tmp/codebase-memory-mcp", "--verify-runtime-assets"],+ )++ def test_runtime_readiness_rejects_multiply_linked_cache_leaves(self):+ with tempfile.TemporaryDirectory() as root, mock.patch.object(+ _cli, "_cache_dir", return_value=Path(root)+ ):+ binary = _cli._bin_path("0.8.1", "standard")+ binary.parent.mkdir(parents=True)+ binary.write_text("binary")+ integrations = binary.parent / _cli._INTEGRATIONS_NAME+ integrations.write_text("integrations")+ os.link(integrations, binary.parent / "integrations-hardlink")++ self.assertFalse(_cli._runtime_set_ready("0.8.1"))++ def test_orphan_reconciliation_rejects_multiply_linked_backup_members(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ binary = directory / "codebase-memory-mcp"+ backup = directory / f".cbm-runtime-backup-{'a' * 32}"+ backup.mkdir()+ (backup / ".retirement-complete").write_bytes(b"")+ member = backup / binary.name+ member.write_text("binary:old")+ os.link(member, directory / "backup-hardlink-copy")++ with mock.patch.object(+ _cli, "_bin_path", return_value=binary+ ), mock.patch.object(+ _cli, "_variant", return_value="standard"+ ), self.assertRaisesRegex(+ RuntimeError, "unsafe package-cache backup member"+ ):+ _cli._runtime_set_ready_locked("test-version")++ self.assertTrue(backup.exists(), "unsafe backup was mutated")+ self.assertFalse((directory / _cli._RUNTIME_LOCK_NAME).exists())++ def test_stalled_lock_creator_never_deletes_successor(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ successor = None++ def publish_successor_then_abort():+ nonlocal successor+ _cli._runtime_lock_claim_observer = None+ successor, _ = _cli._acquire_runtime_lock(directory)+ raise RuntimeError("injected stalled creator abort")++ with mock.patch.object(+ _cli,+ "_runtime_lock_claim_observer",+ side_effect=publish_successor_then_abort,+ ), self.assertRaisesRegex(RuntimeError, "stalled creator abort"):+ _cli._acquire_runtime_lock(directory)++ self.assertIsNotNone(successor)+ self.assertTrue(successor[0].exists())+ _cli._release_runtime_lock(successor)++ def test_expired_lease_never_reclaims_live_owner(self):+ with tempfile.TemporaryDirectory() as root:+ lock_path = Path(root) / _cli._RUNTIME_LOCK_NAME+ owner = {+ "pid": os.getpid(),+ "token": "a" * 32,+ "lease_expires_ms": int((time.time() - 1) * 1000),+ }+ owner_record = f"{json.dumps(owner)}\n"+ lock_path.write_text(owner_record)+ before = lock_path.stat()++ with mock.patch.object(_cli, "_process_is_alive", return_value=True):+ self.assertEqual(+ _cli._try_reclaim_runtime_lock(lock_path, "b" * 32),+ (False, False),+ )+ after = lock_path.stat()+ self.assertEqual(lock_path.read_text(), owner_record)+ self.assertEqual(json.loads(lock_path.read_text())["token"], owner["token"])+ self.assertEqual(after.st_dev, before.st_dev)+ self.assertEqual(after.st_ino, before.st_ino)++ def test_stale_legacy_lock_never_reclaims_live_owner(self):+ with tempfile.TemporaryDirectory() as root:+ lock_path = Path(root) / _cli._RUNTIME_LOCK_NAME+ owner_record = json.dumps(+ {"pid": os.getpid(), "token": "a" * 32}+ ) + "\n"+ lock_path.mkdir()+ (lock_path / "owner.json").write_text(owner_record)+ stale = time.time() - _cli._RUNTIME_LEGACY_STALE_SECONDS - 1+ os.utime(lock_path, (stale, stale))+ before = lock_path.stat()++ with mock.patch.object(_cli, "_process_is_alive", return_value=True):+ self.assertEqual(+ _cli._try_reclaim_runtime_lock(lock_path, "b" * 32),+ (False, False),+ )+ after = lock_path.stat()+ self.assertEqual((lock_path / "owner.json").read_text(), owner_record)+ self.assertEqual(after.st_dev, before.st_dev)+ self.assertEqual(after.st_ino, before.st_ino)++ def test_stale_ownerless_lock_is_reclaimed(self):+ with tempfile.TemporaryDirectory() as root:+ lock_path = Path(root) / _cli._RUNTIME_LOCK_NAME+ lock_path.write_text("")+ stale = time.time() - _cli._RUNTIME_OWNERLESS_STALE_SECONDS - 1+ os.utime(lock_path, (stale, stale))++ self.assertEqual(+ _cli._try_reclaim_runtime_lock(lock_path, "b" * 32),+ (True, False),+ )+ self.assertFalse(lock_path.exists())++ def test_archive_namespace_is_exact_and_ui_has_one_pack(self):+ pack = f"cbm-ui-{'a' * 64}.pack"+ names = (*_cli._WINDOWS_ARCHIVE_NAMES, pack)++ self.assertEqual(+ _cli._validate_archive_names(names, _cli._WINDOWS_ARCHIVE_NAMES, True),+ pack,+ )+ with self.assertRaises(SystemExit):+ _cli._validate_archive_names(+ (*names, "unexpected-root-file"),+ _cli._WINDOWS_ARCHIVE_NAMES,+ True,+ )+ with self.assertRaises(SystemExit):+ _cli._validate_archive_names(+ (*names, f"cbm-ui-{'b' * 64}.pack"),+ _cli._WINDOWS_ARCHIVE_NAMES,+ True,+ )+ with self.assertRaises(SystemExit):+ _cli._validate_archive_names(+ names, _cli._WINDOWS_ARCHIVE_NAMES, False+ )++ def test_ui_zip_extracts_only_the_runtime_set(self):+ pack = f"cbm-ui-{'a' * 64}.pack"+ with tempfile.TemporaryDirectory() as root:+ archive = Path(root) / "release.zip"+ destination = Path(root) / "extract"+ destination.mkdir()+ with zipfile.ZipFile(archive, "w") as zf:+ for name in (*_cli._WINDOWS_ARCHIVE_NAMES, pack):+ zf.writestr(name, name.encode())++ with zipfile.ZipFile(archive) as zf:+ names = _cli._safe_extract_zip(+ zf,+ str(destination),+ _cli._WINDOWS_ARCHIVE_NAMES,+ (_cli._WINDOWS_BINARY_NAME, _cli._INTEGRATIONS_NAME),+ True,+ )++ self.assertEqual(+ names,+ (_cli._WINDOWS_BINARY_NAME, _cli._INTEGRATIONS_NAME, pack),+ )+ self.assertEqual(+ {path.name for path in destination.iterdir()}, set(names)+ )++ def test_unix_tar_rejects_an_unexpected_root_member(self):+ with tempfile.TemporaryDirectory() as root:+ archive = Path(root) / "release.tar.gz"+ with tarfile.open(archive, "w:gz") as tf:+ for name in (*_cli._UNIX_ARCHIVE_NAMES, "unexpected-root-file"):+ data_path = Path(root) / f"fixture-{len(tf.getmembers())}"+ data_path.write_bytes(name.encode())+ tf.add(data_path, arcname=name)+ destination = Path(root) / "extract"+ destination.mkdir()+ with tarfile.open(archive) as tf, self.assertRaises(SystemExit):+ _cli._safe_extract_tar(+ tf,+ str(destination),+ _cli._UNIX_ARCHIVE_NAMES,+ ("codebase-memory-mcp", _cli._INTEGRATIONS_NAME),+ False,+ )++ def test_unix_tar_rejects_hardlink_members(self):+ with tempfile.TemporaryDirectory() as root:+ archive = Path(root) / "release.tar.gz"+ with tarfile.open(archive, "w:gz") as tf:+ info = tarfile.TarInfo("codebase-memory-mcp")+ info.type = tarfile.LNKTYPE+ info.linkname = "cbm-integrations.json"+ tf.addfile(info)+ destination = Path(root) / "extract"+ destination.mkdir()+ with tarfile.open(archive) as tf, self.assertRaises(SystemExit):+ _cli._safe_extract_tar(+ tf,+ str(destination),+ ("codebase-memory-mcp",),+ ("codebase-memory-mcp",),+ False,+ )++ def test_windows_zip_rejects_symlink_metadata(self):+ with tempfile.TemporaryDirectory() as root:+ archive = Path(root) / "release.zip"+ with zipfile.ZipFile(archive, "w") as zf:+ info = zipfile.ZipInfo(_cli._WINDOWS_BINARY_NAME)+ info.create_system = 3+ info.external_attr = (stat.S_IFLNK | 0o777) << 16+ zf.writestr(info, "cbm-integrations.json")+ destination = Path(root) / "extract"+ destination.mkdir()+ with zipfile.ZipFile(archive) as zf, self.assertRaises(SystemExit):+ _cli._safe_extract_zip(+ zf,+ str(destination),+ (_cli._WINDOWS_BINARY_NAME,),+ (_cli._WINDOWS_BINARY_NAME,),+ False,+ )++ def test_readiness_requires_the_complete_selected_variant(self):+ with tempfile.TemporaryDirectory() as root, mock.patch.object(+ _cli, "_cache_dir", return_value=Path(root)+ ):+ with mock.patch.dict(os.environ, {"CBM_VARIANT": "standard"}):+ standard_binary = _cli._bin_path("0.8.1")+ standard_binary.parent.mkdir(parents=True)+ standard_binary.write_text("binary")+ (standard_binary.parent / _cli._INTEGRATIONS_NAME).write_text(+ "integrations"+ )+ self.assertTrue(_cli._runtime_set_ready("0.8.1"))+ (standard_binary.parent / _cli._INTEGRATIONS_NAME).unlink()+ self.assertFalse(_cli._runtime_set_ready("0.8.1"))++ with mock.patch.dict(os.environ, {"CBM_VARIANT": "ui"}):+ ui_binary = _cli._bin_path("0.8.1")+ ui_binary.parent.mkdir(parents=True)+ ui_binary.write_text("binary")+ (ui_binary.parent / _cli._INTEGRATIONS_NAME).write_text(+ "integrations"+ )+ pack_bytes = b"pack"+ pack_name = (+ f"cbm-ui-{hashlib.sha256(pack_bytes).hexdigest()}.pack"+ )+ (ui_binary.parent / pack_name).write_bytes(pack_bytes)+ self.assertTrue(_cli._runtime_set_ready("0.8.1"))+ second_pack = f"cbm-ui-{'b' * 64}.pack"+ (ui_binary.parent / second_pack).write_text("second pack")+ self.assertFalse(_cli._runtime_set_ready("0.8.1"))++ def test_ui_readiness_rejects_digest_mismatched_pack_bytes(self):+ with tempfile.TemporaryDirectory() as root, mock.patch.object(+ _cli, "_cache_dir", return_value=Path(root)+ ), mock.patch.dict(os.environ, {"CBM_VARIANT": "ui"}):+ binary = _cli._bin_path("0.8.1")+ binary.parent.mkdir(parents=True)+ binary.write_text("binary")+ (binary.parent / _cli._INTEGRATIONS_NAME).write_text("integrations")+ authenticated = b"authenticated pack"+ digest = hashlib.sha256(authenticated).hexdigest()+ pack = binary.parent / f"cbm-ui-{digest}.pack"+ pack.write_bytes(b"corrupt pack")++ self.assertFalse(+ _cli._runtime_set_ready("0.8.1"),+ "a well-shaped filename must not authenticate different bytes",+ )++ def test_ui_publication_rejects_digest_mismatched_staged_pack(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ binary_name = "codebase-memory-mcp"+ authenticated = b"authenticated pack"+ pack = (+ f"cbm-ui-{hashlib.sha256(authenticated).hexdigest()}.pack"+ )+ staged_paths = {}+ for name, contents in (+ (binary_name, b"binary"),+ (_cli._INTEGRATIONS_NAME, b"integrations"),+ (pack, b"corrupt pack"),+ ):+ staged = directory / f".stage-{name}"+ staged.write_bytes(contents)+ staged_paths[name] = staged++ with self.assertRaisesRegex(RuntimeError, "digest"):+ _cli._publish_runtime_set(+ staged_paths, directory / binary_name, binary_name, "ui"+ )++ self.assertFalse((directory / binary_name).exists())+ self.assertFalse((directory / _cli._RUNTIME_LOCK_NAME).exists())++ def test_publication_commits_sidecars_before_binary(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ binary_name = "codebase-memory-mcp"+ pack_bytes = b"pack"+ pack = f"cbm-ui-{hashlib.sha256(pack_bytes).hexdigest()}.pack"+ staged_paths = {}+ for name, contents in (+ (binary_name, b"binary"),+ (_cli._INTEGRATIONS_NAME, b"integrations"),+ (pack, pack_bytes),+ ):+ staged = directory / f"stage-{name}"+ staged.write_bytes(contents)+ staged_paths[name] = staged+ committed = []+ replace = os.replace++ def record_replace(source, destination):+ committed.append(Path(destination).name)+ replace(source, destination)++ with mock.patch.object(_cli.os, "replace", side_effect=record_replace):+ _cli._publish_runtime_set(+ staged_paths, directory / binary_name, binary_name, "ui"+ )++ self.assertEqual(+ committed, [_cli._INTEGRATIONS_NAME, pack, binary_name]+ )++ def test_killed_publisher_is_reconciled_by_locked_readiness(self):+ helper_source = r"""+import os+import sys+import time+from pathlib import Path++source_root, directory_raw, staged_raw, marker_raw, crash_name = sys.argv[1:]+sys.path.insert(0, source_root)+from codebase_memory_mcp import _cli++directory = Path(directory_raw)+staged = Path(staged_raw)+marker = Path(marker_raw)+binary_name = "codebase-memory-mcp"+staged_paths = {+ _cli._INTEGRATIONS_NAME: staged / _cli._INTEGRATIONS_NAME,+ binary_name: staged / binary_name,+}+replace = os.replace++def pausing_replace(source, destination):+ replace(source, destination)+ if Path(destination) == directory / crash_name:+ marker.write_text("reached\n")+ while True:+ time.sleep(60)++def verifier(binary):+ if not Path(binary).read_text().startswith("binary:"):+ raise RuntimeError("test binary failed verification")++_cli._publish_runtime_set(+ staged_paths,+ directory / binary_name,+ binary_name,+ "standard",+ replace_file=pausing_replace,+ verifier=verifier,+)+"""+ binary_name = "codebase-memory-mcp"+ for crash_name, expected_ready in (+ (_cli._INTEGRATIONS_NAME, False),+ (binary_name, True),+ ):+ with self.subTest(crash_name=crash_name), tempfile.TemporaryDirectory() as root:+ root_path = Path(root)+ directory = root_path / "destination"+ staged = root_path / "staged"+ marker = root_path / "crash-reached"+ directory.mkdir()+ staged.mkdir()+ (directory / binary_name).write_text("corrupt:old")+ (directory / _cli._INTEGRATIONS_NAME).write_text(+ "integrations:old"+ )+ (staged / binary_name).write_text("binary:candidate")+ (staged / _cli._INTEGRATIONS_NAME).write_text(+ "integrations:candidate"+ )+ environment = os.environ.copy()+ environment["PYTHONPYCACHEPREFIX"] = str(root_path / "pycache")+ process = subprocess.Popen(+ [+ sys.executable,+ "-c",+ helper_source,+ str(PACKAGE_ROOT / "src"),+ str(directory),+ str(staged),+ str(marker),+ crash_name,+ ],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.PIPE,+ text=True,+ env=environment,+ )+ try:+ deadline = time.monotonic() + 10+ while not marker.exists() and time.monotonic() < deadline:+ if process.poll() is not None:+ stderr = process.communicate()[1]+ self.fail(+ "publication helper exited before crash gate: "+ f"{stderr}"+ )+ time.sleep(0.01)+ self.assertTrue(+ marker.exists(),+ "publication helper did not reach crash gate",+ )+ backups = [+ path+ for path in directory.iterdir()+ if path.name.startswith(".cbm-runtime-backup-")+ ]+ self.assertEqual(len(backups), 1)+ self.assertTrue(backups[0].is_dir())+ self.assertTrue(+ (backups[0] / ".retirement-complete").is_file()+ )++ process.kill()+ process.wait(5)+ self.assertNotEqual(process.returncode, 0)++ def verifier(binary):+ if not Path(binary).read_text().startswith("binary:"):+ raise RuntimeError("test binary failed verification")++ with mock.patch.object(+ _cli, "_bin_path", return_value=directory / binary_name+ ), mock.patch.object(+ _cli, "_variant", return_value="standard"+ ), mock.patch.object(+ _cli, "_verify_candidate", side_effect=verifier+ ):+ ready = _cli._runtime_set_ready_locked("test-version")+ self.assertEqual(ready, expected_ready)+ if not ready:+ self.assertEqual(+ (directory / binary_name).read_text(),+ "corrupt:old",+ )+ self.assertEqual(+ (directory / _cli._INTEGRATIONS_NAME).read_text(),+ "integrations:old",+ )+ retry_staged = root_path / "retry-staged"+ retry_staged.mkdir()+ retry_paths = {+ binary_name: retry_staged / binary_name,+ _cli._INTEGRATIONS_NAME: retry_staged+ / _cli._INTEGRATIONS_NAME,+ }+ retry_paths[binary_name].write_text("binary:candidate")+ retry_paths[_cli._INTEGRATIONS_NAME].write_text(+ "integrations:candidate"+ )+ _cli._publish_runtime_set(+ retry_paths,+ directory / binary_name,+ binary_name,+ "standard",+ verifier=verifier,+ )++ self.assertEqual(+ (directory / binary_name).read_text(), "binary:candidate"+ )+ self.assertEqual(+ (directory / _cli._INTEGRATIONS_NAME).read_text(),+ "integrations:candidate",+ )+ self.assertFalse(+ any(+ path.name.startswith(".cbm-runtime-backup-")+ for path in directory.iterdir()+ )+ )+ self.assertFalse(+ (directory / _cli._RUNTIME_LOCK_NAME).exists()+ )+ finally:+ if process.poll() is None:+ process.kill()+ process.wait(5)+ if process.stderr is not None:+ process.stderr.close()++ def test_publication_failure_restores_prior_complete_runtime_set(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ binary_name = "codebase-memory-mcp"+ old_pack_bytes = b"old pack"+ old_pack = f"cbm-ui-{hashlib.sha256(old_pack_bytes).hexdigest()}.pack"+ (directory / binary_name).write_text("binary:old")+ (directory / _cli._INTEGRATIONS_NAME).write_text("integrations:old")+ (directory / old_pack).write_bytes(old_pack_bytes)++ candidate_pack_bytes = b"candidate pack"+ candidate_pack = (+ f"cbm-ui-{hashlib.sha256(candidate_pack_bytes).hexdigest()}.pack"+ )+ staged_paths = {}+ for name, contents in (+ (binary_name, b"binary:candidate"),+ (_cli._INTEGRATIONS_NAME, b"integrations:candidate"),+ (candidate_pack, candidate_pack_bytes),+ ):+ staged = directory / f"stage-{name}"+ staged.write_bytes(contents)+ staged_paths[name] = staged++ replace = os.replace+ failed = False+ retired = []++ def fail_binary_publish(source, destination):+ nonlocal failed+ source = Path(source)+ destination = Path(destination)+ if destination.parent.name.startswith(".cbm-runtime-backup-"):+ retired.append(source.name)+ if destination == directory / binary_name and not failed:+ failed = True+ raise OSError("injected binary publication failure")+ replace(source, destination)++ with self.assertRaises(OSError):+ _cli._publish_runtime_set(+ staged_paths,+ directory / binary_name,+ binary_name,+ "ui",+ replace_file=fail_binary_publish,+ )++ self.assertTrue(failed)+ self.assertEqual(retired[0], binary_name)+ self.assertEqual((directory / binary_name).read_text(), "binary:old")+ self.assertEqual(+ (directory / _cli._INTEGRATIONS_NAME).read_text(),+ "integrations:old",+ )+ self.assertEqual((directory / old_pack).read_bytes(), old_pack_bytes)+ self.assertFalse((directory / candidate_pack).exists())+ self.assertFalse(+ any(+ path.name.startswith(".cbm-runtime-backup-")+ for path in directory.iterdir()+ )+ )++ def test_concurrent_publishers_preserve_the_first_complete_winner(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ binary_name = "codebase-memory-mcp"++ def stages(tag):+ pack_bytes = f"pack:{tag}".encode()+ pack = (+ f"cbm-ui-{hashlib.sha256(pack_bytes).hexdigest()}.pack"+ )+ result = {}+ for name, contents in (+ (binary_name, f"binary:{tag}".encode()),+ (_cli._INTEGRATIONS_NAME, f"integrations:{tag}".encode()),+ (pack, pack_bytes),+ ):+ staged = directory / f".stage-{tag}-{name}"+ staged.write_bytes(contents)+ result[name] = staged+ return result, pack++ first_stages, first_pack = stages("first")+ second_stages, second_pack = stages("second")+ first_holds_lock = threading.Event()+ allow_first = threading.Event()+ second_observed_lock = threading.Event()+ errors = []+ replace = os.replace+ read_lock_owner = _cli._read_runtime_lock_owner++ def pause_first(source, destination):+ replace(source, destination)+ if Path(destination) == directory / binary_name:+ first_holds_lock.set()+ if not allow_first.wait(5):+ raise RuntimeError("test did not release first publisher")++ def observe_waiter(lock_path):+ if threading.current_thread().name == "publisher-second":+ second_observed_lock.set()+ return read_lock_owner(lock_path)++ def publish(label, staged_paths, replace_file=None):+ try:+ _cli._publish_runtime_set(+ staged_paths,+ directory / binary_name,+ binary_name,+ "ui",+ replace_file=replace_file,+ )+ except Exception as exc: # surfaced on the test thread below+ errors.append((label, exc))++ first = threading.Thread(+ name="publisher-first",+ target=publish,+ args=("first", first_stages, pause_first),+ )+ second = threading.Thread(+ name="publisher-second",+ target=publish,+ args=("second", second_stages),+ )+ with mock.patch.object(+ _cli,+ "_read_runtime_lock_owner",+ side_effect=observe_waiter,+ ):+ first.start()+ try:+ self.assertTrue(first_holds_lock.wait(2))+ second.start()+ self.assertTrue(second_observed_lock.wait(2))+ finally:+ allow_first.set()+ first.join(5)+ if second.ident is not None:+ second.join(5)++ self.assertFalse(first.is_alive())+ self.assertFalse(second.is_alive())+ self.assertEqual(errors, [])+ self.assertEqual(+ (directory / binary_name).read_bytes(), b"binary:first"+ )+ self.assertEqual(+ (directory / _cli._INTEGRATIONS_NAME).read_bytes(),+ b"integrations:first",+ )+ self.assertEqual(+ (directory / first_pack).read_bytes(), b"pack:first"+ )+ self.assertFalse((directory / second_pack).exists())+ self.assertFalse((directory / _cli._RUNTIME_LOCK_NAME).exists())++ def test_failure_never_deletes_a_complete_foreign_winner(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ binary_name = "codebase-memory-mcp"+ old_pack_bytes = b"pack:old"+ old_pack = (+ f"cbm-ui-{hashlib.sha256(old_pack_bytes).hexdigest()}.pack"+ )+ (directory / binary_name).write_bytes(b"binary:old")+ (directory / _cli._INTEGRATIONS_NAME).write_bytes(+ b"integrations:old"+ )+ (directory / old_pack).write_bytes(old_pack_bytes)++ candidate_pack_bytes = b"pack:candidate"+ candidate_pack = (+ f"cbm-ui-{hashlib.sha256(candidate_pack_bytes).hexdigest()}.pack"+ )+ staged_paths = {}+ for name, contents in (+ (binary_name, b"binary:candidate"),+ (_cli._INTEGRATIONS_NAME, b"integrations:candidate"),+ (candidate_pack, candidate_pack_bytes),+ ):+ staged = directory / f".stage-candidate-{name}"+ staged.write_bytes(contents)+ staged_paths[name] = staged++ foreign_pack_bytes = b"pack:foreign"+ foreign_pack = (+ f"cbm-ui-{hashlib.sha256(foreign_pack_bytes).hexdigest()}.pack"+ )+ replace = os.replace+ injected = False++ def install_foreign_winner(source, destination):+ nonlocal injected+ source = Path(source)+ destination = Path(destination)+ if destination == directory / binary_name and not injected:+ injected = True+ for path in directory.iterdir():+ if path.name.startswith("cbm-ui-") and path.name.endswith(+ ".pack"+ ):+ path.unlink()+ (directory / _cli._INTEGRATIONS_NAME).write_bytes(+ b"integrations:foreign"+ )+ (directory / foreign_pack).write_bytes(foreign_pack_bytes)+ (directory / binary_name).write_bytes(b"binary:foreign")+ raise OSError("simulated non-cooperating winner")+ replace(source, destination)++ _cli._publish_runtime_set(+ staged_paths,+ directory / binary_name,+ binary_name,+ "ui",+ replace_file=install_foreign_winner,+ )++ self.assertTrue(injected)+ self.assertEqual(+ (directory / binary_name).read_bytes(), b"binary:foreign"+ )+ self.assertEqual(+ (directory / _cli._INTEGRATIONS_NAME).read_bytes(),+ b"integrations:foreign",+ )+ self.assertEqual(+ (directory / foreign_pack).read_bytes(), foreign_pack_bytes+ )+ self.assertFalse((directory / candidate_pack).exists())+ self.assertFalse((directory / old_pack).exists())+ self.assertFalse(+ any(+ path.name.startswith(".cbm-runtime-backup-")+ for path in directory.iterdir()+ )+ )if __name__ == "__main__":diff --git a/pkg/scoop/codebase-memory-mcp.json b/pkg/scoop/codebase-memory-mcp.jsonindex d4853c492..f4ae23c1b 100644--- a/pkg/scoop/codebase-memory-mcp.json+++ b/pkg/scoop/codebase-memory-mcp.json@@ -1,6 +1,6 @@{"version": "0.8.1",- "description": "Fast code intelligence engine for AI coding agents — single static binary MCP server",+ "description": "Fast code intelligence engine — native executable with verified runtime assets","homepage": "https://github.com/DeusData/codebase-memory-mcp","license": "MIT","architecture": {@@ -10,9 +10,6 @@"bin": "codebase-memory-mcp.exe"}},- "post_install": [- "& \"$dir\\codebase-memory-mcp.exe\" install -y 2>&1 | Out-Null"- ],"checkver": {"github": "https://github.com/DeusData/codebase-memory-mcp"},diff --git a/pkg/winget/manifests/d/DeusData/CodebaseMemoryMcp/0.8.1/DeusData.CodebaseMemoryMcp.locale.en-US.yaml b/pkg/winget/manifests/d/DeusData/CodebaseMemoryMcp/0.8.1/DeusData.CodebaseMemoryMcp.locale.en-US.yamlindex 7377238a4..a9440ad0f 100644--- a/pkg/winget/manifests/d/DeusData/CodebaseMemoryMcp/0.8.1/DeusData.CodebaseMemoryMcp.locale.en-US.yaml+++ b/pkg/winget/manifests/d/DeusData/CodebaseMemoryMcp/0.8.1/DeusData.CodebaseMemoryMcp.locale.en-US.yaml@@ -10,11 +10,13 @@ License: MITLicenseUrl: https://github.com/DeusData/codebase-memory-mcp/blob/main/LICENSEShortDescription: Fast code intelligence engine for AI coding agentsDescription: |-- codebase-memory-mcp is a single static binary MCP server that indexes codebases- at extreme speed and exposes 14 MCP tools for AI coding agents. Full indexes an- average repository in milliseconds, the Linux kernel (28M LOC) in 3 minutes.- Supports 155 languages via vendored tree-sitter grammars. Zero dependencies.- Plug and play across 11 coding agents including Claude Code, Codex CLI, and Zed.+ codebase-memory-mcp is a native MCP server distributed as a verified runtime+ set. The portable archive keeps its authenticated release-owned assets with the+ executable registered by WinGet. It indexes codebases at extreme speed and+ exposes 14 MCP tools for AI coding agents. Full indexes an average repository+ in milliseconds, the Linux kernel (28M LOC) in 3 minutes. Supports 155 languages+ via vendored tree-sitter grammars. No hosted service or API key. Plug and play+ across 11 coding agents including Claude Code, Codex CLI, and Zed.Moniker: codebase-memory-mcpTags:- mcpdiff --git a/scripts/README.md b/scripts/README.mdindex 9e9a5d42d..619959ebe 100644--- a/scripts/README.md+++ b/scripts/README.md@@ -4,7 +4,7 @@only a canonical leg script may exercise the product.* Local CI, PR CI, thedry run and the release all call the SAME files below — venues differ only inhost specs, architecture and inputs, never in what a leg does. Platform-differences (arm64 sanitizer flags, the Windows launcher, the linux portable+differences (arm64 sanitizer flags, native Windows behavior, the Linux portablebinary) live INSIDE these scripts, once, never per-venue.`tests/test_venue_parity_contract.sh` (run as Step 0j of every test leg) turnsany violation — inline harness logic in a workflow, a bypassed wrapper, a@@ -17,12 +17,13 @@ codes) and rejects unknown flags with exit 2 + `Please consult --help.`| leg | entry | what a run gives you ||---|---|---|-| **test** | `test.sh` | DEFAULT = the venue leg: static contracts (Step 0a–0j) + CLEAN ASan+UBSan build + all suites via the parallel harness + prod-binary guards. `--suites a,b` = iteration mode (incremental rebuild, subset, seconds). `--tsan` = the ThreadSanitizer leg. CLANGARM64 gets CI's trap-UBSan flags automatically. |-| **build** | `build.sh` | CLEAN production build (+ launcher on Windows). ccache via `env.sh` makes repeats fast; `CCACHE_COMPILERCHECK=content` guarantees a hit is byte-identical to a cold compile — never stale. `--with-ui`, `--version`, `STATIC=1`, `BUILD_DIR=`. |+| **test** | `test.sh` | DEFAULT = the venue leg: static contracts (Step 0a–0r) + CLEAN ASan+UBSan build + all suites via the parallel harness + prod-binary guards. `--suites a,b` = iteration mode (incremental rebuild, subset, seconds). `--tsan` = the ThreadSanitizer leg. CLANGARM64 gets CI's trap-UBSan flags automatically. |+| **package wrappers** | `ci/test-package-wrappers.sh` | Go, npm, and PyPI runtime-set publication/lock suites on the current host. CI runs the same entry on Linux and Windows so both platform lock implementations gate. |+| **build** | `build.sh` | CLEAN production runtime set (native executable + authenticated integration asset; `--with-ui` adds one content-addressed UI pack). ccache via `env.sh` makes repeats fast; `CCACHE_COMPILERCHECK=content` guarantees a hit is byte-identical to a cold compile — never stale. `--version`, `STATIC=1`, `BUILD_DIR=`. || **lint** | `lint.sh` | clang-tidy + cppcheck + clang-format (+ no-skips policy). `--ci` = the CI gate set (no clang-tidy). Drives the same make targets as `make lint`/`lint-ci`. |-| **smoke (unix)** | `smoke-local.sh` | Stages a full release fixture, serves it on a kernel-assigned port, runs `smoke-test.sh` (ALL phases incl. download/install/update E2E) inside a disposable HOME/XDG/TMP sandbox. `ui` variant makes a missing embedded UI a FAILURE. `CBM_SMOKE_ARTIFACT_DIR` = smoke an extracted release artifact verbatim (release mode). |-| **smoke (windows)** | `../test-infrastructure/vm/vm-smoke.sh` | Same contract for the launcher+payload pair, plus the user-PATH registry guard (prepare/verify/cleanup). |-| **smoke-invariants** | `smoke-invariants.sh` | The "shipped binary does not fail" battery (MCP handshake, all tools invocable, malformed-input resilience) — no fixture server, no install E2E. `smoke.yml` runs it on the WIDEST build-from-source matrix (incl. older-glibc legs the release artifacts cannot cover). |+| **smoke (unix)** | `smoke-local.sh` | Stages a full release fixture, serves it on a kernel-assigned port, runs `smoke-test.sh` (ALL phases incl. download/install/update E2E) inside a disposable HOME/XDG/TMP sandbox. `ui` variant makes a missing verified UI pack a FAILURE. `CBM_SMOKE_ARTIFACT_DIR` = smoke an extracted release artifact verbatim (release mode). |+| **smoke (windows)** | `../test-infrastructure/vm/vm-smoke.sh` | Same verified runtime-set contract on the real Windows VM, plus the user-PATH registry guard (prepare/verify/cleanup). |+| **smoke-invariants** | `smoke-invariants.sh` | Production-path resilience battery (MCP handshake, all tools invocable, malformed-input handling, supervised crash/hang recovery) — no fixture server or install E2E. `smoke.yml` runs an explicitly seam-enabled build on the WIDEST source matrix; release artifacts remain seam-free and use the release-shaped smoke legs above. || **soak** | `soak-legs.sh` | The release-gating soak SEQUENCE: `quick` then `query-leak` (the #581 detector — never reindexes, so RSS growth = query-path leak), each guarded by a completion-summary check. `--legs quick` for the ASan single-leg variant. Duration is per leg. |Internal harnesses — never called directly by a venue (the contract forbidsdiff --git a/scripts/build.sh b/scripts/build.shindex 0b44dcbf4..7b6f9dace 100755--- a/scripts/build.sh+++ b/scripts/build.sh@@ -3,7 +3,7 @@## Usage:# scripts/build.sh # Standard binary-# scripts/build.sh --with-ui # Binary with embedded UI+# scripts/build.sh --with-ui # Binary + external UI asset pack# scripts/build.sh --help # Full usage# scripts/build.sh --version v0.8.0 # With version stamp# scripts/build.sh --arch x86_64 # Force x86_64 build@@ -29,7 +29,7 @@ from current sources; a cache hit is byte-identical to a cold compile byconstruction (CCACHE_COMPILERCHECK=content).Options:- --with-ui Embed the web UI (builds the frontend first; needs node).+ --with-ui Build the web UI as a content-addressed sidecar (needs node).--version V Stamp the version string (release venue passes the tag).--arch ARCH Force target arch (arm64 | x86_64), e.g. under Rosetta.-h, --help This text.@@ -158,7 +158,7 @@ fi# Stage the integration-template asset next to the binary so the dev/CI build# mirrors the release archive layout. The binary resolves cbm-integrations.json-# next to itself, in $CBM_ASSETS_DIR, or under ~/.cbm/assets/<version>/; a plain+# next to itself, in $CBM_ASSETS_DIR, or under ~/.cbm/assets/<sha256>/; a plain# build/c binary has none of those, so install/uninstall (which render the# templates to verify hash and ownership) would fail closed exactly as they do# for a user who deleted the file. Copying it here keeps `install` working@@ -166,4 +166,20 @@ fi# then see the same adjacency.cp "$ROOT/assets/cbm-integrations.json" "$BUILD_DIR/cbm-integrations.json"+if $WITH_UI; then+ shopt -s nullglob+ UI_PACKS=("$BUILD_DIR"/cbm-ui-*.pack)+ shopt -u nullglob+ if [ "${#UI_PACKS[@]}" -ne 1 ]; then+ echo "build.sh: UI build did not produce exactly one content-addressed asset pack" >&2+ exit 1+ fi+ UI_PACK_NAME="$(basename "${UI_PACKS[0]}")"+ if ! [[ "$UI_PACK_NAME" =~ ^cbm-ui-[0-9a-f]{64}\.pack$ ]]; then+ echo "build.sh: invalid UI asset pack name: $UI_PACK_NAME" >&2+ exit 1+ fi+ echo "=== UI assets: ${UI_PACKS[0]} ==="+fi+echo "=== Build complete: ${BUILD_DIR}/codebase-memory-mcp ==="diff --git a/scripts/ci/append-vt-notes.sh b/scripts/ci/append-vt-notes.shindex 56f5b42f4..588046174 100755--- a/scripts/ci/append-vt-notes.sh+++ b/scripts/ci/append-vt-notes.sh@@ -1,29 +1,255 @@#!/usr/bin/env bash-# Append the Security Verification section to the release notes: per-binary-# sha256 + VirusTotal links. This step only runs after check-virustotal.sh-# passed, and that gate is ZERO tolerance — any detection blocks the release —-# so "0 detections" here is a verified statement, never an assumption.-# Expects: GH_TOKEN, VERSION; run from the verify job workspace (binaries/).+# Idempotently publish the exact VirusTotal scope and measured result evidence+# after check-virustotal.sh has passed.set -euo pipefail-TABLE="\n\n## Security Verification\n\n"-TABLE+="All release binaries scanned with 70+ antivirus engines — **0 detections**.\n\n"-TABLE+="| Binary | SHA-256 | VirusTotal |\n"-TABLE+="|--------|---------|------------|\n"--for bin in binaries/codebase-memory-mcp-*; do- [ -f "$bin" ] || continue- name=$(basename "$bin")- sha256=$(sha256sum "$bin" 2>/dev/null | awk '{print $1}' \- || shasum -a 256 "$bin" | awk '{print $1}')- label=$(echo "$name" | sed 's/^codebase-memory-mcp-//' | sed 's/\.exe$//')- short="${sha256:0:20}..."- vt_url="https://www.virustotal.com/gui/file/${sha256}/detection"- TABLE+="| \`${label}\` | \`${short}\` | [0 detections ✅](${vt_url}) |\n"-done--CURRENT=$(gh release view "$VERSION" \- --json body --jq '.body // ""' --repo "$GITHUB_REPOSITORY")-printf '%s%b' "$CURRENT" "$TABLE" > /tmp/release_notes.md+: "${GH_TOKEN:?append-vt-notes: GH_TOKEN is required}"+: "${VERSION:?append-vt-notes: VERSION is required}"+: "${GITHUB_REPOSITORY:?append-vt-notes: GITHUB_REPOSITORY is required}"++VT_ASSOCIATIONS="${VT_ASSOCIATIONS:-binaries/associations.tsv}"+VT_RESULTS_PATH="${VT_RESULTS_PATH:-binaries/vt-results.tsv}"+WORK="$(mktemp -d "${TMPDIR:-/tmp}/cbm-vt-notes.XXXXXX")"+trap 'rm -rf "$WORK"' EXIT++gh release view "$VERSION" \+ --json body --jq '.body // ""' --repo "$GITHUB_REPOSITORY" > "$WORK/current.md"++python3 - "$VT_ASSOCIATIONS" "$VT_RESULTS_PATH" "$WORK/current.md" "$WORK/updated.md" \+ "$GITHUB_REPOSITORY" "$VERSION" <<'PY'+from __future__ import annotations++import csv+import pathlib+import re+import sys+import urllib.parse+from typing import Dict, List, Sequence, Tuple+++START = "<!-- cbm-security-verification:start -->"+END = "<!-- cbm-security-verification:end -->"+ASSOCIATION_FIELDS = (+ "association_type",+ "archive",+ "archive_sha256",+ "variant",+ "kind",+ "member",+ "asset_path",+ "mime",+ "scan_path",+ "object_sha256",+ "size",+)+RESULT_FIELDS = (+ "scan_path",+ "sha256",+ "size",+ "association_count",+ "completed_engines",+ "total_engines",+ "malicious",+ "suspicious",+ "analysis_id",+ "microsoft_category",+ "microsoft_engine_version",+ "microsoft_engine_update",+ "virustotal_url",+)+++def fail(message: str) -> None:+ raise SystemExit(f"append-vt-notes: {message}")+++def read_tsv(+ path: pathlib.Path,+ marker: str,+ fields: Sequence[str],+) -> Tuple[Dict[str, int], List[Dict[str, str]]]:+ if path.is_symlink() or not path.is_file() or path.stat().st_size > 16 * 1024 * 1024:+ fail(f"missing, unsafe or oversized evidence file: {path}")+ lines = path.read_text(encoding="utf-8").splitlines()+ if not lines or lines[0] != f"# {marker}":+ fail(f"wrong evidence marker in {path}")+ metadata: Dict[str, int] = {}+ cursor = 1+ while cursor < len(lines) and lines[cursor].startswith("# "):+ key, separator, raw_value = lines[cursor][2:].partition("=")+ if not separator or not key or key in metadata or not raw_value.isdigit():+ fail(f"malformed evidence metadata in {path}")+ metadata[key] = int(raw_value)+ cursor += 1+ reader = csv.DictReader(lines[cursor:], delimiter="\t")+ if tuple(reader.fieldnames or ()) != tuple(fields):+ fail(f"unexpected TSV header in {path}")+ rows = list(reader)+ if any(None in row or any(row.get(field) is None for field in fields) for row in rows):+ fail(f"TSV row has missing or surplus cells in {path}")+ if not rows:+ fail(f"empty evidence rows in {path}")+ return metadata, rows+++association_path = pathlib.Path(sys.argv[1])+results_path = pathlib.Path(sys.argv[2])+current_path = pathlib.Path(sys.argv[3])+updated_path = pathlib.Path(sys.argv[4])+repository = sys.argv[5]+version = sys.argv[6]+if re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository) is None or not version:+ fail("unsafe repository or version for public evidence links")+asset_base = (+ f"https://github.com/{repository}/releases/download/"+ f"{urllib.parse.quote(version, safe='')}"+)+association_meta, associations = read_tsv(+ association_path,+ "cbm-release-scan-associations-v2",+ ASSOCIATION_FIELDS,+)+result_meta, results = read_tsv(+ results_path,+ "cbm-virustotal-results-v1",+ RESULT_FIELDS,+)+if association_meta.get("associations") != len(associations):+ fail("association manifest count does not match its rows")+if result_meta.get("scan_objects") != len(results):+ fail("VirusTotal result count does not match its rows")+if result_meta.get("associations") != len(associations):+ fail("VirusTotal results do not cover the association manifest")++results_by_path: Dict[str, Dict[str, str]] = {}+association_counts: Dict[str, int] = {}+executable_paths = {+ association["scan_path"]+ for association in associations+ if association["kind"] == "binary"+}+for association in associations:+ scan_path = association["scan_path"]+ association_counts[scan_path] = association_counts.get(scan_path, 0) + 1+for result in results:+ scan_path = result["scan_path"]+ if scan_path in results_by_path:+ fail(f"duplicate VirusTotal result path: {scan_path}")+ for numeric in (+ "size",+ "association_count",+ "completed_engines",+ "total_engines",+ "malicious",+ "suspicious",+ ):+ if not result[numeric].isdigit():+ fail(f"malformed numeric result field {numeric}: {scan_path}")+ if int(result["malicious"]) != 0 or int(result["suspicious"]) != 0:+ fail(f"detected object reached release-note publication: {scan_path}")+ if (+ re.fullmatch(r"[0-9a-f]{64}", result["sha256"]) is None+ or result["virustotal_url"]+ != f"https://www.virustotal.com/gui/file/{result['sha256']}/detection"+ ):+ fail(f"result SHA/link is malformed or mismatched: {scan_path}")+ if int(result["association_count"]) != association_counts.get(scan_path):+ fail(f"result association count mismatch: {scan_path}")+ if scan_path in executable_paths:+ if result["microsoft_category"] not in {"undetected", "harmless"}:+ fail(f"executable result lacks a decisive clean Microsoft verdict: {scan_path}")+ if not result["microsoft_engine_version"] or not result["microsoft_engine_update"]:+ fail(f"executable result lacks Microsoft version evidence: {scan_path}")+ results_by_path[scan_path] = result+if set(results_by_path) != set(association_counts):+ fail("VirusTotal result paths differ from association paths")+for association in associations:+ result = results_by_path[association["scan_path"]]+ if (+ result["sha256"] != association["object_sha256"]+ or result["size"] != association["size"]+ ):+ fail(f"result hash/size differs from association: {association['scan_path']}")++archive_rows = [row for row in associations if row["association_type"] == "archive"]+member_rows = [row for row in associations if row["association_type"] == "member"]+asset_rows = [row for row in associations if row["association_type"] == "pack_asset"]+if len(archive_rows) != association_meta.get("archives"):+ fail("downloadable archive association count is inconsistent")+archive_names = [row["archive"] for row in archive_rows]+if len(set(archive_names)) != len(archive_names):+ fail("downloadable archive association is duplicated")+archive_hashes = {row["archive"]: row["archive_sha256"] for row in archive_rows}+if any(row["archive_sha256"] != row["object_sha256"] for row in archive_rows):+ fail("downloadable archive SHA is not bound to its scan object")+if any(archive_hashes.get(row["archive"]) != row["archive_sha256"] for row in associations):+ fail("member/asset association is not bound to its downloadable archive")++engine_counts = [int(row["completed_engines"]) for row in results]+minimum = min(engine_counts)+maximum = max(engine_counts)+policy = result_meta.get("min_engines_policy")+if policy is None or minimum < policy:+ fail("result engine counts do not satisfy their recorded policy")+engine_range = str(minimum) if minimum == maximum else f"{minimum}–{maximum}"++section = [+ START,+ "## Security Verification",+ "",+ (+ f"VirusTotal completed **{len(results)} distinct byte objects** covering "+ f"**{len(associations)} exact release associations**: "+ f"{len(archive_rows)} downloadable archives, {len(member_rows)} archive members, "+ f"and {len(asset_rows)} independently extracted UI-pack assets."+ ),+ "",+ (+ f"Every object returned **0 malicious and 0 suspicious** verdicts with "+ f"{engine_range} decisive engine results (required minimum: {policy})."+ ),+ (+ f"Microsoft returned a decisive clean verdict for all "+ f"{len(executable_paths)} executable objects."+ ),+ "",+ (+ "Durable public evidence: "+ f"[associations]({asset_base}/virustotal-associations.tsv), "+ f"[exact scan set]({asset_base}/virustotal-scan-set.tsv), "+ f"[per-object results and report links]({asset_base}/virustotal-results.tsv), "+ f"[evidence checksums]({asset_base}/virustotal-evidence-checksums.txt)."+ ),+ "",+ "| Downloadable archive | SHA-256 | Engines | VirusTotal |",+ "|---|---|---:|---|",+]+for association in sorted(archive_rows, key=lambda row: row["archive"]):+ result = results_by_path[association["scan_path"]]+ sha256 = result["sha256"]+ section.append(+ f"| `{association['archive']}` | `{sha256}` | "+ f"{result['completed_engines']} | [0 detections]({result['virustotal_url']}) |"+ )+section.append(END)+replacement = "\n".join(section)++current = current_path.read_text(encoding="utf-8")+start_count = current.count(START)+end_count = current.count(END)+if start_count != end_count or start_count > 1:+ fail("existing release notes contain malformed verification markers")+if start_count == 1:+ if current.index(START) >= current.index(END):+ fail("existing release-note verification markers are reversed")+ pattern = re.compile(re.escape(START) + r".*?" + re.escape(END), re.DOTALL)+ updated, replacements = pattern.subn(replacement, current, count=1)+ if replacements != 1:+ fail("existing release-note verification section could not be replaced")+else:+ updated = current.rstrip() + ("\n\n" if current.strip() else "") + replacement + "\n"+updated_path.write_text(updated, encoding="utf-8")+PY+gh release edit "$VERSION" \- --notes-file /tmp/release_notes.md --repo "$GITHUB_REPOSITORY"+ --notes-file "$WORK/updated.md" --repo "$GITHUB_REPOSITORY"diff --git a/scripts/ci/check-binary-composition.sh b/scripts/ci/check-binary-composition.shindex 1a0167067..43864e634 100755--- a/scripts/ci/check-binary-composition.sh+++ b/scripts/ci/check-binary-composition.sh@@ -3,12 +3,15 @@# shipped artifact.## Microsoft Defender's ML classifier flagged the v0.9.1-rc.1 binaries. The-# hardening pass that followed *removed capability* — an executable stack, an-# in-process updater, test-only environment seams, the embedded HTTP/UI server-# and its process enumerator in the standard build. Each of those regresses-# invisibly: one restored #include, one Makefile source list edit, one revived-# call site, and nothing else in CI notices — the binary just quietly gets its-# malware-shaped surface back and the next release gets flagged again.+# hardening pass that followed removed capability or opaque asset bytes — an+# executable stack, an in-process updater, test-only environment seams,+# embedded integration programs, and the in-image frontend bundle. Each of+# those regresses invisibly: one restored #include, one Makefile source-list+# edit, one revived call site, and nothing else in CI notices — the binary just+# quietly restores capability or opaque bytes that this hardening boundary is+# intended to exclude. Their removal reduces attack surface and makes release+# contents independently inspectable; it does not establish which feature, if+# any, caused an opaque third-party ML verdict.## This script is the proof that each removal stayed removed. It asserts only# NEGATIVE properties (needle absent), plus one canary string we know ships,@@ -39,16 +42,18 @@ esac# S6: worker/Windows test seams read these env vars. A release binary that# still honours them lets any process on the box steer the indexer's child-# processes and file placement — and CBM_TEST_* in a shipped binary is exactly-# the "debug/injection hooks" shape AV heuristics score on.+# processes and file placement. Their absence is a release-security boundary;+# no claim is made about whether a third-party classifier weighs them.SEAM_NEEDLES=('CBM_TEST_WORKER_DESCENDANT_PID_FILE'- 'CBM_TEST_WINDOWS_USER_PATH_RUN_ID'+ 'CBM_TEST_CRASH_ON'+ 'CBM_TEST_HANG_ON')-# The in-process updater (download-and-replace-own-binary) is the single most-# malware-shaped behaviour we ever shipped; updates now run from install.sh-# out-of-process. These four needles cover both halves of what was removed:+# The in-process updater combined network download with replacement of its own+# executable. That dual-use behavior is no longer needed in the daemon; updates+# now run from install.sh out-of-process. These four needles cover both halves+# of what was removed:# the download base URL, the checksum URL built on top of it, the GitHub API# release query of the daemon's background version check, and that request's# Accept header (which survives even if the URL is ever assembled at runtime).@@ -72,8 +77,8 @@ SQLITE_LOADEXT_NEEDLES=()# The standard artifact must not contain the UI's HTTP server at all: an-# unauthenticated localhost listener plus a process enumerator is precisely the-# behaviour pair a classifier reads as a backdoor. Needles are split across+# unauthenticated localhost listener plus a process enumerator is unnecessary+# capability in the standard composition. Needles are split across# both UI translation units and are independent of each other, so a refactor of# any single one cannot silently disarm the assertion:# 'HTTP/1.1 %d %s' httpd.c response-status writer@@ -95,8 +100,9 @@ UI_HTTP_NEEDLES=(# The binary used to embed nine complete shebang'd shell scripts, their# PowerShell/.cmd twins and two node:child_process client modules — script-# bodies written to disk at 0755, which is precisely the text surface-# Defender's ML scored Trojan:Script/Wacatac.B!ml. They now ship in+# bodies written to disk at 0755. Keeping those programs outside the native+# image narrows executable surface and lets each component be inspected and+# scanned independently. They now ship in# cbm-integrations.json (the binary embeds only its SHA-256); these needles# prove the removal stayed removed. Source-level enforcement lives in# tests/test_no_embedded_scripts_contract.sh; this is the shipped-artifact@@ -108,6 +114,17 @@ SCRIPT_NEEDLES=('node:child_process')+# UI frontend bytes belong exclusively in the independently scannable pack.+# These are structural bytes from the pack header and Vite's emitted index,+# selected to avoid generic HTML grammar strings that legitimately occur in the+# language parsers linked into every binary.+UI_ASSET_BYTE_NEEDLES=(+ 'CBMUIPK'+ '<!doctype html>'+ '<html lang="en" class="dark">'+ '<script type="module" crossorigin'+)+# Canary: proves the needle scan can actually see this file's strings. Without# it, handing the gate a gzip, a stub or a 0-byte file would pass every# absence assertion. 168+ occurrences in a real artifact, 0 in anything else.@@ -268,8 +285,8 @@ check_file() {'this is not one of our artifacts, or its strings are unreadable (packed/compressed/truncated) — every absence assertion below would pass vacuously'# A1 — executable stack (ELF only). Every Linux artifact of v0.9.1-rc.1- # shipped GNU_STACK RWE: a writable+executable stack, which no modern- # binary has and which any classifier weighs heavily.+ # shipped GNU_STACK RWE. A writable+executable stack is unnecessary here+ # and weakens exploit mitigations, independently of any scanner verdict.if [ "$fmt" = elf ]; thenif ! resolve_elf_reader; thenecho "FAIL: no readelf/llvm-readelf/objdump available; cannot assert" \@@ -301,16 +318,11 @@ check_file() {done# Sweep for seams nobody thought to pin: a new CBM_TEST_* env var added to# production code lands here on its first release, not on the next audit.- # Two seams remain in release artifacts BY DECISION, so the wildcard is an- # allowlist rather than a blanket ban: scripts/smoke-test.sh runs against the- # real release artifact, and these are what let it do so honestly —- # CRASH_ON/HANG_ON inject the faults that prove supervisor recovery, and- # WINDOWS_USER_PATH_RUN_ID is what stops the PATH smoke from writing the- # tester's actual PATH. Deleting them would trade genuine release-artifact- # coverage for a cosmetic win. Anything NOT on this list is a novel seam and- # fails, which is the property that matters: the list can only shrink by- # decision, never grow by accident.- seam_allowed='CBM_TEST_CRASH_ON CBM_TEST_HANG_ON CBM_TEST_WINDOWS_USER_PATH_RUN_ID'+ # One narrowly validated seam remains in Windows release artifacts by+ # decision: WINDOWS_USER_PATH_RUN_ID redirects the artifact smoke away from+ # the tester's actual user PATH. Crash/hang injectors are test-build-only and+ # are explicitly forbidden above. Anything else is novel and fails.+ seam_allowed='CBM_TEST_WINDOWS_USER_PATH_RUN_ID'seam_unexpected=''for found in $(LC_ALL=C grep -a -o -E 'CBM_TEST_[A-Za-z0-9_]+' "$file" 2>/dev/null |sort -u || true); do@@ -352,19 +364,12 @@ check_file() {# A5 — UI/HTTP subsystem, standard artifacts only.#- # NOT YET ENFORCED. src/ui/{config,http_server,layout3d,httpd,embedded_stub}.c- # are still in PROD_SRCS, and the standard build merely substitutes empty- # embedded assets — so the HTTP server and its popen("ps … | grep") process- # enumerator are linked into artifacts that can never serve a UI. Excluding- # them is a real refactor: four files outside src/ui (src/main.c,- # src/daemon/host.c, src/daemon/application.c, src/mcp/index_supervisor.c)- # reference UI symbols, including the daemon that serves the UI.- #- # Until that lands, this assertion reports rather than fails. A gate everyone- # knows is red teaches people to ignore gates, and a known-failing check has- # no more enforcement value than this note — but the needles are kept live and- # exercised so that the day the split lands, flipping CBM_CHECK_UI_ABSENT=1- # (then making it the default) is a one-line change and not a rewrite.+ # The temporary standard variant still links the UI control/HTTP code but+ # substitutes the no-I/O asset-pack stub, so it cannot publish a UI. That+ # variant remains only for before/after VirusTotal verification and is then+ # deprecated in favor of one UI-capable product composition. Until that+ # evidence gate is complete, this assertion remains an explicit diagnostic;+ # CBM_CHECK_UI_ABSENT=1 is available for any future true no-UI composition.if [ "$is_ui" -eq 1 ]; thenprintf 'n/a %-22s %s: UI artifact, HTTP server ships here by design\n' \A5-no-ui-http "$token"@@ -379,32 +384,24 @@ check_file() {ui_hits=$((ui_hits + 1))fidone- printf 'INFO %-22s %s: %d/%d UI/HTTP needles present (no-UI split pending; set CBM_CHECK_UI_ABSENT=1 to enforce)\n' \+ printf 'INFO %-22s %s: %d/%d UI/HTTP needles present (temporary standard variant; set CBM_CHECK_UI_ABSENT=1 to enforce a true no-UI composition)\n' \A5-no-ui-http "$token" "$ui_hits" "${#UI_HTTP_NEEDLES[@]}"fi- # A6 — embedded integration-script text. Enforced on standard artifacts:- # every C-source template moved into cbm-integrations.json, so a hit means- # one crept back in. The ui artifact additionally embeds the RAW frontend- # bundle (scripts/embed-frontend.sh stores plain bytes), whose minified JS- # may legitimately contain e.g. "#!" sequences we do not control — so ui- # reports rather than fails until that is measured on a real ui build,- # mirroring A5's honest-INFO pattern. Flip CBM_CHECK_UI_SCRIPTS_ABSENT=1- # to enforce there too.- if [ "$is_ui" -eq 1 ] && [ "${CBM_CHECK_UI_SCRIPTS_ABSENT:-0}" != "1" ]; then- script_hits=0- for needle in "${SCRIPT_NEEDLES[@]}"; do- if LC_ALL=C grep -a -q -F -e "$needle" "$file"; then- script_hits=$((script_hits + 1))- fi- done- printf 'INFO %-22s %s: %d/%d script needles present (raw frontend bundle; set CBM_CHECK_UI_SCRIPTS_ABSENT=1 to enforce)\n' \- A6-no-embedded-scripts "$token" "$script_hits" "${#SCRIPT_NEEDLES[@]}"- else- for needle in "${SCRIPT_NEEDLES[@]}"; do- assert_absent "$file" "$token" A6-no-embedded-scripts "$needle"- done- fi+ # A6 — embedded integration-script text. Every variant is now subject to+ # the same hard gate: the UI frontend is external, so it can no longer mask+ # a returned shebang or node:child_process body in the native image.+ for needle in "${SCRIPT_NEEDLES[@]}"; do+ assert_absent "$file" "$token" A6-no-embedded-scripts "$needle"+ done++ # A7 — UI pack/header and frontend HTML/script bytes. The pack is scanned as+ # its own release file; none of its raw frontend bytes belongs in any+ # ELF/Mach-O/PE variant. Applying this to standard too makes the boundary a+ # product-wide invariant rather than relying on path classification.+ for needle in "${UI_ASSET_BYTE_NEEDLES[@]}"; do+ assert_absent "$file" "$token" A7-no-ui-asset-bytes "$needle"+ done}# ── Walk the targets ────────────────────────────────────────────────diff --git a/scripts/ci/check-virustotal.sh b/scripts/ci/check-virustotal.shindex 8adc52a10..8f446ad30 100755--- a/scripts/ci/check-virustotal.sh+++ b/scripts/ci/check-virustotal.sh@@ -1,114 +1,726 @@#!/usr/bin/env bash-# Wait for VirusTotal scans to complete and check results.-# Expects: VT_API_KEY, VT_ANALYSIS (comma-separated "file=URL" pairs)+# Verify that the VirusTotal action submitted and completed exactly the+# content-bound scan set produced by extract-release-archives.sh.+#+# Required: VT_API_KEY, VT_ANALYSIS, VT_EXPECTED_SCAN_SET, VT_ASSOCIATIONS+# Workflow policy: MIN_ENGINES=50, zero malicious, zero suspicious.+# Optional: VT_RESULTS_PATH, VT_REQUEST_INTERVAL_SECONDS,+# VT_POLL_TIMEOUT_SECONDS, VT_CURL_TIMEOUT_SECONDS.set -euo pipefail-MIN_ENGINES=60-rm -f /tmp/vt_gate_fail--echo "=== Waiting for VirusTotal scans to fully complete ==="--echo "$VT_ANALYSIS" | tr ',' '\n' | while IFS= read -r entry; do- [ -z "$entry" ] && continue- FILE=$(echo "$entry" | cut -d'=' -f1)- URL=$(echo "$entry" | cut -d'=' -f2-)- BASENAME=$(basename "$FILE")-- # Extract base64 analysis ID from URL- ANALYSIS_ID=$(echo "$URL" | sed -n 's|.*/file-analysis/\([^/]*\)/.*|\1|p')- if [ -z "$ANALYSIS_ID" ]; then- ANALYSIS_ID=$(echo "$URL" | grep -oE '[a-f0-9]{64}')- if [ -z "$ANALYSIS_ID" ]; then- echo "BLOCKED: Cannot parse VirusTotal URL: $URL"- echo "FAIL" >> /tmp/vt_gate_fail- continue- fi- fi-- # Poll until completed (max 120 min)- SCAN_COMPLETE=false- for attempt in $(seq 1 720); do- RESULT=$(curl -sf --max-time 10 \- -H "x-apikey: $VT_API_KEY" \- "https://www.virustotal.com/api/v3/analyses/$ANALYSIS_ID" 2>/dev/null || echo "")-- if [ -z "$RESULT" ]; then- echo " $BASENAME: waiting (attempt $attempt)..."- sleep 10- continue- fi-- # Line 1 is the CSV summary; any further lines name a flagging engine.- # The engine names are what a detection is actionable ON: the FP submission- # has to go to a specific vendor, and "is this the known-noisy one or a new- # family" is the first question asked. Reporting only counts sent the reader- # to the web UI for the one fact the gate already had in hand.- REPORT=$(echo "$RESULT" | python3 -c "-import json, sys-d = json.loads(sys.stdin.read())-attrs = d.get('data', {}).get('attributes', {})-status = attrs.get('status', 'queued')-stats = attrs.get('stats', {})-malicious = stats.get('malicious', 0)-suspicious = stats.get('suspicious', 0)-undetected = stats.get('undetected', 0)-harmless = stats.get('harmless', 0)-total = sum(stats.values())-completed = malicious + suspicious + undetected + harmless-print(f'{status},{malicious},{suspicious},{completed},{total}')-for engine, r in sorted((attrs.get('results') or {}).items()):- if r.get('category') in ('malicious', 'suspicious'):- label = r.get('result') or r.get('category')- version = r.get('engine_version') or '?'- updated = r.get('engine_update') or '?'- print(f'{engine} = {label} (engine {version}, defs {updated})')-" 2>/dev/null || echo "queued,0,0,0,0")-- STATS=$(echo "$REPORT" | head -1)- DETECTIONS=$(echo "$REPORT" | tail -n +2)- STATUS=$(echo "$STATS" | cut -d',' -f1)- MALICIOUS=$(echo "$STATS" | cut -d',' -f2)- SUSPICIOUS=$(echo "$STATS" | cut -d',' -f3)- COMPLETED=$(echo "$STATS" | cut -d',' -f4)- TOTAL=$(echo "$STATS" | cut -d',' -f5)-- if [ "$STATUS" = "completed" ]; then- SCAN_COMPLETE=true- if [ "$COMPLETED" -lt "$MIN_ENGINES" ]; then- echo "NOTE: $BASENAME completed with only $COMPLETED/$TOTAL engines (< $MIN_ENGINES)"- fi- if [ "$MALICIOUS" -gt 0 ] || [ "$SUSPICIOUS" -gt 0 ]; then- echo "BLOCKED: $BASENAME flagged ($MALICIOUS malicious, $SUSPICIOUS suspicious / $COMPLETED engines)"- if [ -n "$DETECTIONS" ]; then- echo "$DETECTIONS" | while IFS= read -r detection; do- [ -n "$detection" ] && echo " detected by: $detection"- done- else- # Counts say something flagged but no engine is named: report that- # rather than printing nothing, so the gap is visible instead of- # looking like a detection-free block.- echo " detected by: <engine names unavailable in the analysis response>"- fi- echo " $URL"- echo "FAIL" >> /tmp/vt_gate_fail- else- echo "OK: $BASENAME clean ($COMPLETED engines, 0 detections)"- fi- break- fi-- echo " $BASENAME: $COMPLETED/$TOTAL engines ($STATUS, attempt $attempt)..."- sleep 10- done-- if [ "$SCAN_COMPLETE" != "true" ]; then- echo "WARNING: $BASENAME scan did not complete in time"- echo "FAIL" >> /tmp/vt_gate_fail- fi-done--if [ -f /tmp/vt_gate_fail ]; then- echo "BLOCKED: One or more VirusTotal checks failed"+command -v python3 >/dev/null 2>&1 || {+ echo "BLOCKED: python3 is required for the VirusTotal gate" >&2exit 1-fi-echo "=== All VirusTotal scans passed ==="+}+command -v curl >/dev/null 2>&1 || {+ echo "BLOCKED: curl is required for the VirusTotal gate" >&2+ exit 1+}++python3 - <<'PY'+from __future__ import annotations++import csv+import hashlib+import json+import os+import pathlib+import re+import stat+import subprocess+import sys+import tempfile+import time+import urllib.parse+from collections import deque+from dataclasses import dataclass+from typing import Deque, Dict, List, Optional, Sequence, Tuple+++class GateError(Exception):+ pass+++SCAN_FIELDS = (+ "scan_path",+ "sha256",+ "size",+ "association_count",+ "association_kinds",+)+ASSOCIATION_FIELDS = (+ "association_type",+ "archive",+ "archive_sha256",+ "variant",+ "kind",+ "member",+ "asset_path",+ "mime",+ "scan_path",+ "object_sha256",+ "size",+)+RESULT_FIELDS = (+ "scan_path",+ "sha256",+ "size",+ "association_count",+ "completed_engines",+ "total_engines",+ "malicious",+ "suspicious",+ "analysis_id",+ "microsoft_category",+ "microsoft_engine_version",+ "microsoft_engine_update",+ "virustotal_url",+)+SHA256_RE = re.compile(r"\A[0-9a-f]{64}\Z")+ANALYSIS_ID_RE = re.compile(r"\A[A-Za-z0-9_+/-]+={0,2}\Z")+ALLOWED_STATS = {+ "confirmed-timeout",+ "timeout",+ "failure",+ "harmless",+ "undetected",+ "suspicious",+ "malicious",+ "type-unsupported",+}+DECISIVE_STATS = ("malicious", "suspicious", "undetected", "harmless")+ALLOWED_STATUS = {"queued", "in-progress", "completed"}+++@dataclass(frozen=True)+class ExpectedObject:+ scan_path: str+ local_path: pathlib.Path+ sha256: str+ size: int+ association_count: int+ association_kinds: frozenset[str]++ @property+ def requires_microsoft(self) -> bool:+ return "binary" in self.association_kinds+++@dataclass(frozen=True)+class Submission:+ expected: ExpectedObject+ analysis_id: str+ action_url: str+++@dataclass(frozen=True)+class CompletedResult:+ submission: Submission+ completed_engines: int+ total_engines: int+ malicious: int+ suspicious: int+ microsoft_category: str+ microsoft_engine_version: str+ microsoft_engine_update: str+++def required_env(name: str) -> str:+ value = os.environ.get(name)+ if value is None or value == "":+ raise GateError(f"required environment value is empty: {name}")+ return value+++def parse_int_env(name: str, default: str, *, minimum: int) -> int:+ raw = os.environ.get(name, default)+ if not raw.isdigit() or int(raw) < minimum:+ raise GateError(f"{name} must be an integer >= {minimum}")+ return int(raw)+++def sha256_file(path: pathlib.Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def parse_versioned_tsv(+ path: pathlib.Path,+ *,+ marker: str,+ fields: Sequence[str],+) -> Tuple[Dict[str, int], List[Dict[str, str]]]:+ if path.is_symlink() or not path.is_file():+ raise GateError(f"expected evidence manifest is not a regular file: {path}")+ if path.stat().st_size > 16 * 1024 * 1024:+ raise GateError(f"expected evidence manifest is unexpectedly large: {path}")+ lines = path.read_text(encoding="utf-8").splitlines()+ if not lines or lines[0] != f"# {marker}":+ raise GateError(f"expected evidence manifest marker is missing: {marker}")+ metadata: Dict[str, int] = {}+ cursor = 1+ while cursor < len(lines) and lines[cursor].startswith("# "):+ raw = lines[cursor][2:]+ key, separator, value = raw.partition("=")+ if not separator or not key or key in metadata or not value.isdigit():+ raise GateError(f"malformed or duplicate evidence metadata: {raw}")+ metadata[key] = int(value)+ cursor += 1+ reader = csv.DictReader(lines[cursor:], delimiter="\t")+ if tuple(reader.fieldnames or ()) != tuple(fields):+ raise GateError("evidence TSV header is malformed or unexpected")+ rows = list(reader)+ if any(None in row or any(row.get(field) is None for field in fields) for row in rows):+ raise GateError("evidence TSV row has missing or surplus cells")+ if not rows:+ raise GateError("expected scan set is empty")+ return metadata, rows+++def load_expected(path: pathlib.Path) -> Tuple[List[ExpectedObject], int]:+ metadata, rows = parse_versioned_tsv(+ path,+ marker="cbm-release-scan-set-v1",+ fields=SCAN_FIELDS,+ )+ expected_count = metadata.get("scan_objects")+ associations = metadata.get("associations")+ if expected_count != len(rows) or associations is None or associations < len(rows):+ raise GateError("scan-set metadata does not match its rows")+ objects: List[ExpectedObject] = []+ seen_paths: set[str] = set()+ association_total = 0+ for row in rows:+ scan_path = row["scan_path"]+ pure = pathlib.PurePosixPath(scan_path)+ if (+ pure.is_absolute()+ or len(pure.parts) != 2+ or pure.parts[0] != "objects"+ or pure.parts[1] in ("", ".", "..")+ or scan_path != pure.as_posix()+ or scan_path in seen_paths+ ):+ raise GateError(f"invalid or duplicate scan path in expected set: {scan_path}")+ seen_paths.add(scan_path)+ sha256 = row["sha256"]+ if SHA256_RE.fullmatch(sha256) is None:+ raise GateError(f"invalid SHA-256 in expected set: {scan_path}")+ if not row["size"].isdigit() or not row["association_count"].isdigit():+ raise GateError(f"invalid size/count in expected set: {scan_path}")+ size = int(row["size"])+ association_count = int(row["association_count"])+ kinds = row["association_kinds"].split(",")+ allowed_kinds = {"archive", "binary", "pack", "runtime", "ui_asset"}+ if (+ association_count < 1+ or any(not kind or kind not in allowed_kinds for kind in kinds)+ or kinds != sorted(set(kinds))+ ):+ raise GateError(f"unassociated object in expected set: {scan_path}")+ local_path = path.parent.joinpath(*pure.parts)+ try:+ mode = local_path.lstat().st_mode+ except FileNotFoundError as error:+ raise GateError(f"expected scan object is missing: {scan_path}") from error+ if not stat.S_ISREG(mode):+ raise GateError(f"expected scan object is not a regular file: {scan_path}")+ actual_size = local_path.stat().st_size+ if actual_size != size or sha256_file(local_path) != sha256:+ raise GateError(f"expected scan object changed after extraction: {scan_path}")+ association_total += association_count+ objects.append(+ ExpectedObject(+ scan_path=scan_path,+ local_path=local_path.absolute(),+ sha256=sha256,+ size=size,+ association_count=association_count,+ association_kinds=frozenset(kinds),+ )+ )+ if association_total != associations:+ raise GateError("scan-set association counts do not match manifest metadata")+ return objects, associations+++def validate_associations(+ path: pathlib.Path,+ *,+ objects: Sequence[ExpectedObject],+ expected_associations: int,+) -> None:+ metadata, rows = parse_versioned_tsv(+ path,+ marker="cbm-release-scan-associations-v2",+ fields=ASSOCIATION_FIELDS,+ )+ if (+ metadata.get("associations") != expected_associations+ or metadata.get("scan_objects") != len(objects)+ or len(rows) != expected_associations+ ):+ raise GateError("association manifest metadata does not match the expected scan set")+ expected_by_path = {item.scan_path: item for item in objects}+ counts: Dict[str, int] = {}+ kinds: Dict[str, set[str]] = {}+ seen: set[Tuple[str, str, str, str]] = set()+ archive_hashes: Dict[str, str] = {}+ for row in rows:+ if row["association_type"] != "archive":+ continue+ archive = row["archive"]+ if not archive or archive in archive_hashes or row["archive_sha256"] != row["object_sha256"]:+ raise GateError(f"malformed or duplicate archive association: {archive}")+ archive_hashes[archive] = row["archive_sha256"]+ for row in rows:+ association_type = row["association_type"]+ key = (association_type, row["archive"], row["member"], row["asset_path"])+ if key in seen:+ raise GateError(f"duplicate release association: {key}")+ seen.add(key)+ if association_type not in {"archive", "member", "pack_asset"} or not row["archive"]:+ raise GateError(f"malformed release association: {key}")+ if archive_hashes.get(row["archive"]) != row["archive_sha256"]:+ raise GateError(f"association is not bound to its archive object: {key}")+ if association_type == "archive":+ semantic_valid = (+ not row["member"]+ and not row["asset_path"]+ and row["kind"] == "archive"+ )+ elif association_type == "member":+ semantic_valid = bool(row["member"]) and not row["asset_path"]+ else:+ semantic_valid = bool(row["member"] and row["asset_path"] and row["mime"]) and row["kind"] == "ui_asset"+ if not semantic_valid:+ raise GateError(f"malformed release association semantics: {key}")+ expected = expected_by_path.get(row["scan_path"])+ if expected is None:+ raise GateError(f"association maps outside expected scan set: {key}")+ if (+ row["object_sha256"] != expected.sha256+ or not row["size"].isdigit()+ or int(row["size"]) != expected.size+ or SHA256_RE.fullmatch(row["archive_sha256"]) is None+ ):+ raise GateError(f"association hash/size is not content-bound: {key}")+ counts[expected.scan_path] = counts.get(expected.scan_path, 0) + 1+ kinds.setdefault(expected.scan_path, set()).add(row["kind"])+ if set(counts) != set(expected_by_path):+ raise GateError("association manifest does not map every expected scan object")+ for scan_path, expected in expected_by_path.items():+ if counts[scan_path] != expected.association_count:+ raise GateError(f"association count differs from expected scan set: {scan_path}")+ if frozenset(kinds[scan_path]) != expected.association_kinds:+ raise GateError(f"association kinds differ from expected scan set: {scan_path}")+++def output_aliases(objects: Sequence[ExpectedObject], manifest: pathlib.Path) -> Dict[str, ExpectedObject]:+ aliases: Dict[str, ExpectedObject] = {}+ cwd = pathlib.Path.cwd().absolute()+ for item in objects:+ relative_from_cwd = os.path.relpath(item.local_path, cwd)+ candidates = {+ item.scan_path,+ item.local_path.name,+ str(item.local_path),+ pathlib.PurePosixPath(relative_from_cwd).as_posix(),+ pathlib.PurePosixPath(manifest.parent.name, item.scan_path).as_posix(),+ f"./{pathlib.PurePosixPath(relative_from_cwd).as_posix()}",+ }+ for alias in candidates:+ previous = aliases.get(alias)+ if previous is not None and previous.scan_path != item.scan_path:+ raise GateError(f"ambiguous expected action-output alias: {alias}")+ aliases[alias] = item+ return aliases+++def parse_analysis_id(url: str) -> str:+ parsed = urllib.parse.urlsplit(url)+ if parsed.scheme != "https" or parsed.hostname not in {"www.virustotal.com", "virustotal.com"}:+ raise GateError(f"malformed VirusTotal analysis URL: {url}")+ parts = parsed.path.split("/")+ try:+ index = parts.index("file-analysis")+ analysis_id = urllib.parse.unquote(parts[index + 1])+ except (ValueError, IndexError):+ raise GateError(f"malformed VirusTotal analysis URL: {url}") from None+ if ANALYSIS_ID_RE.fullmatch(analysis_id) is None:+ raise GateError(f"malformed VirusTotal analysis id in URL: {url}")+ return analysis_id+++def parse_action_output(+ raw: str,+ *,+ objects: Sequence[ExpectedObject],+ manifest: pathlib.Path,+) -> List[Submission]:+ if not raw:+ raise GateError("VirusTotal action output is empty")+ aliases = output_aliases(objects, manifest)+ submissions: Dict[str, Submission] = {}+ used_ids: set[str] = set()+ entries = raw.split(",")+ if any(entry == "" or entry != entry.strip() for entry in entries):+ raise GateError("VirusTotal action output has an empty or whitespace-padded entry")+ for entry in entries:+ filename, separator, url = entry.partition("=")+ if not separator or not filename or not url:+ raise GateError(f"malformed VirusTotal action output entry: {entry}")+ expected = aliases.get(filename)+ if expected is None:+ raise GateError(f"VirusTotal action returned an unexpected path: {filename}")+ if expected.scan_path in submissions:+ raise GateError(f"VirusTotal action returned a duplicate path: {filename}")+ analysis_id = parse_analysis_id(url)+ if analysis_id in used_ids:+ raise GateError("VirusTotal action reused one analysis for multiple scan objects")+ used_ids.add(analysis_id)+ submissions[expected.scan_path] = Submission(expected, analysis_id, url)+ expected_paths = {item.scan_path for item in objects}+ actual_paths = set(submissions)+ if actual_paths != expected_paths:+ missing = sorted(expected_paths - actual_paths)+ unexpected = sorted(actual_paths - expected_paths)+ raise GateError(+ f"VirusTotal action output is partial or unexpected: missing={missing}, unexpected={unexpected}"+ )+ return [submissions[path] for path in sorted(submissions)]+++def nonnegative_int(value: object, label: str) -> int:+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ raise GateError(f"malformed VirusTotal statistic: {label}")+ return value+++def one_line(value: object) -> str:+ return " ".join(str(value).split())+++def required_one_line_string(value: object, label: str) -> str:+ if not isinstance(value, str):+ raise GateError(f"VirusTotal field is not a string: {label}")+ normalized = " ".join(value.split())+ if not normalized:+ raise GateError(f"VirusTotal field is empty: {label}")+ return normalized+++def parse_completed(document: object, submission: Submission) -> Tuple[str, Optional[CompletedResult], List[str]]:+ if not isinstance(document, dict):+ raise GateError("VirusTotal response root is not an object")+ data = document.get("data")+ if not isinstance(data, dict):+ raise GateError("VirusTotal response has no analysis data object")+ if data.get("type") != "analysis":+ raise GateError(f"VirusTotal response is not an analysis for {submission.expected.scan_path}")+ response_id = data.get("id")+ if response_id != submission.analysis_id:+ raise GateError(f"VirusTotal response id mismatch for {submission.expected.scan_path}")+ attributes = data.get("attributes")+ if not isinstance(attributes, dict):+ raise GateError("VirusTotal response has no analysis attributes")+ status = attributes.get("status")+ if status not in ALLOWED_STATUS:+ raise GateError(f"VirusTotal response has invalid status: {status!r}")+ if status != "completed":+ return str(status), None, []++ meta = document.get("meta")+ file_info = meta.get("file_info") if isinstance(meta, dict) else None+ if not isinstance(file_info, dict):+ raise GateError(f"completed analysis has no file_info: {submission.expected.scan_path}")+ actual_sha = file_info.get("sha256")+ actual_size = file_info.get("size")+ if actual_sha != submission.expected.sha256 or nonnegative_int(actual_size, "file_info.size") != submission.expected.size:+ raise GateError(+ f"completed analysis hash/size does not match submitted object: {submission.expected.scan_path}"+ )++ stats = attributes.get("stats")+ if not isinstance(stats, dict) or not stats:+ raise GateError(f"completed analysis has no stats: {submission.expected.scan_path}")+ missing = sorted(ALLOWED_STATS - set(stats))+ unknown = sorted(set(stats) - ALLOWED_STATS)+ if missing or unknown:+ raise GateError(+ f"completed analysis has missing/unknown stats categories: "+ f"missing={missing}, unknown={unknown}"+ )+ normalized = {key: nonnegative_int(value, f"stats.{key}") for key, value in stats.items()}+ completed = sum(normalized[key] for key in DECISIVE_STATS)+ total = sum(normalized.values())+ malicious = normalized["malicious"]+ suspicious = normalized["suspicious"]++ detections: List[str] = []+ results = attributes.get("results")+ microsoft_category = ""+ microsoft_engine_version = ""+ microsoft_engine_update = ""+ detail_detections = {"malicious": 0, "suspicious": 0}+ if results is not None:+ if not isinstance(results, dict):+ raise GateError("VirusTotal per-engine results are malformed")+ for engine, result in sorted(results.items()):+ if not isinstance(engine, str) or not isinstance(result, dict):+ raise GateError("VirusTotal per-engine result entry is malformed")+ category = result.get("category")+ if category not in ALLOWED_STATS:+ raise GateError(f"VirusTotal engine {engine} has invalid category: {category!r}")+ if category in {"malicious", "suspicious"}:+ detail_detections[category] += 1+ label = one_line(result.get("result") or category)+ version = one_line(result.get("engine_version") or "?")+ updated = one_line(result.get("engine_update") or "?")+ detections.append(+ f"{one_line(engine)} = {label} (engine {version}, defs {updated})"+ )+ if engine == "Microsoft":+ microsoft_category = str(category)+ microsoft_engine_version = required_one_line_string(+ result.get("engine_version"), "Microsoft.engine_version"+ )+ microsoft_engine_update = required_one_line_string(+ result.get("engine_update"), "Microsoft.engine_update"+ )+ for category, count in detail_detections.items():+ if count > normalized[category]:+ raise GateError(+ f"per-engine {category} results contradict aggregate stats: "+ f"{submission.expected.scan_path}"+ )+ if submission.expected.requires_microsoft:+ if microsoft_category not in DECISIVE_STATS:+ raise GateError(+ f"completed executable analysis has no decisive Microsoft result: "+ f"{submission.expected.scan_path}"+ )+ if normalized[microsoft_category] < 1:+ raise GateError(+ f"Microsoft category is inconsistent with aggregate stats: "+ f"{submission.expected.scan_path}"+ )+ if not microsoft_engine_version or not microsoft_engine_update:+ raise GateError(+ f"completed executable analysis has incomplete Microsoft version evidence: "+ f"{submission.expected.scan_path}"+ )+ return (+ "completed",+ CompletedResult(+ submission,+ completed,+ total,+ malicious,+ suspicious,+ microsoft_category,+ microsoft_engine_version,+ microsoft_engine_update,+ ),+ detections,+ )+++def fetch_analysis(api_key: str, analysis_id: str, curl_timeout: int) -> Optional[object]:+ encoded_id = urllib.parse.quote(analysis_id, safe="")+ response = subprocess.run(+ [+ "curl",+ "-sf",+ "--max-time",+ str(curl_timeout),+ "-H",+ f"x-apikey: {api_key}",+ f"https://www.virustotal.com/api/v3/analyses/{encoded_id}",+ ],+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ check=False,+ )+ if response.returncode != 0 or not response.stdout:+ return None+ try:+ return json.loads(response.stdout)+ except (UnicodeDecodeError, json.JSONDecodeError) as error:+ raise GateError(f"VirusTotal returned malformed JSON for analysis {analysis_id}") from error+++def write_results(+ path: pathlib.Path,+ *,+ results: Sequence[CompletedResult],+ associations: int,+ min_engines: int,+) -> None:+ if os.path.lexists(path) and path.is_symlink():+ raise GateError(f"results path is a symlink: {path}")+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))+ temporary = pathlib.Path(temporary_name)+ try:+ with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle:+ handle.write("# cbm-virustotal-results-v1\n")+ handle.write(f"# scan_objects={len(results)}\n")+ handle.write(f"# associations={associations}\n")+ handle.write(f"# min_engines_policy={min_engines}\n")+ handle.write(f"# min_completed_engines={min(item.completed_engines for item in results)}\n")+ handle.write(f"# max_completed_engines={max(item.completed_engines for item in results)}\n")+ writer = csv.DictWriter(+ handle,+ fieldnames=RESULT_FIELDS,+ delimiter="\t",+ lineterminator="\n",+ )+ writer.writeheader()+ for item in sorted(results, key=lambda result: result.submission.expected.scan_path):+ expected = item.submission.expected+ writer.writerow(+ {+ "scan_path": expected.scan_path,+ "sha256": expected.sha256,+ "size": expected.size,+ "association_count": expected.association_count,+ "completed_engines": item.completed_engines,+ "total_engines": item.total_engines,+ "malicious": item.malicious,+ "suspicious": item.suspicious,+ "analysis_id": item.submission.analysis_id,+ "microsoft_category": item.microsoft_category,+ "microsoft_engine_version": item.microsoft_engine_version,+ "microsoft_engine_update": item.microsoft_engine_update,+ "virustotal_url": f"https://www.virustotal.com/gui/file/{expected.sha256}/detection",+ }+ )+ handle.flush()+ os.fsync(handle.fileno())+ os.chmod(temporary, 0o600)+ os.replace(temporary, path)+ finally:+ if os.path.lexists(temporary):+ temporary.unlink()+++def main() -> None:+ api_key = required_env("VT_API_KEY")+ raw_analysis = required_env("VT_ANALYSIS")+ expected_manifest = pathlib.Path(required_env("VT_EXPECTED_SCAN_SET")).absolute()+ associations_manifest = pathlib.Path(required_env("VT_ASSOCIATIONS")).absolute()+ min_engines = parse_int_env("MIN_ENGINES", "50", minimum=1)+ request_interval = parse_int_env("VT_REQUEST_INTERVAL_SECONDS", "15", minimum=0)+ poll_timeout = parse_int_env("VT_POLL_TIMEOUT_SECONDS", "7200", minimum=1)+ curl_timeout = parse_int_env("VT_CURL_TIMEOUT_SECONDS", "15", minimum=1)+ results_path = pathlib.Path(+ os.environ.get("VT_RESULTS_PATH", str(expected_manifest.with_name("vt-results.tsv")))+ ).absolute()+ if os.path.lexists(results_path):+ if results_path.is_symlink() or not results_path.is_file():+ raise GateError(f"unsafe pre-existing VT results path: {results_path}")+ results_path.unlink()++ expected, associations = load_expected(expected_manifest)+ validate_associations(+ associations_manifest,+ objects=expected,+ expected_associations=associations,+ )+ submissions = parse_action_output(+ raw_analysis,+ objects=expected,+ manifest=expected_manifest,+ )+ print(+ f"=== VirusTotal exact-set gate: {len(submissions)} distinct objects, "+ f"{associations} associations, >= {min_engines} decisive engines each ==="+ )++ pending: Deque[Submission] = deque(submissions)+ completed: List[CompletedResult] = []+ failures: List[str] = []+ attempts: Dict[str, int] = {item.expected.scan_path: 0 for item in submissions}+ started = time.monotonic()+ next_request_at = started+ while pending:+ now = time.monotonic()+ if now - started >= poll_timeout:+ names = [item.expected.scan_path for item in pending]+ raise GateError(f"VirusTotal analyses did not complete within {poll_timeout}s: {names}")+ if now < next_request_at:+ time.sleep(min(next_request_at - now, 1.0))+ continue+ submission = pending.popleft()+ attempts[submission.expected.scan_path] += 1+ document = fetch_analysis(api_key, submission.analysis_id, curl_timeout)+ next_request_at = time.monotonic() + request_interval+ if document is None:+ pending.append(submission)+ if attempts[submission.expected.scan_path] == 1 or attempts[submission.expected.scan_path] % 4 == 0:+ print(f" {submission.expected.scan_path}: API unavailable; will retry round-robin")+ continue+ status, result, detections = parse_completed(document, submission)+ if status != "completed" or result is None:+ pending.append(submission)+ if attempts[submission.expected.scan_path] == 1 or attempts[submission.expected.scan_path] % 4 == 0:+ print(f" {submission.expected.scan_path}: {status}; will retry round-robin")+ continue+ completed.append(result)+ if result.completed_engines < min_engines:+ message = (+ f"{submission.expected.scan_path} completed with only "+ f"{result.completed_engines}/{result.total_engines} decisive engines "+ f"(< {min_engines})"+ )+ failures.append(message)+ print(f"BLOCKED: {message}")+ elif result.malicious or result.suspicious:+ message = (+ f"{submission.expected.scan_path} flagged "+ f"({result.malicious} malicious, {result.suspicious} suspicious / "+ f"{result.completed_engines} decisive engines)"+ )+ failures.append(message)+ print(f"BLOCKED: {message}")+ if detections:+ for detection in detections:+ print(f" detected by: {detection}")+ else:+ print(" detected by: <engine names unavailable in the analysis response>")+ print(+ f" https://www.virustotal.com/gui/file/"+ f"{submission.expected.sha256}/detection"+ )+ else:+ print(+ f"OK: {submission.expected.scan_path} clean "+ f"({result.completed_engines}/{result.total_engines} decisive/total engines)"+ )++ completed_paths = {item.submission.expected.scan_path for item in completed}+ expected_paths = {item.expected.scan_path for item in submissions}+ if completed_paths != expected_paths or len(completed) != len(submissions):+ raise GateError("completed VirusTotal set differs from the exact submitted set")+ write_results(+ results_path,+ results=completed,+ associations=associations,+ min_engines=min_engines,+ )+ if failures:+ print(f"VirusTotal completed-set evidence: {results_path}")+ raise GateError(f"{len(failures)} VirusTotal object(s) failed release policy")+ print(f"=== All {len(completed)} exact VirusTotal objects passed; results: {results_path} ===")+++try:+ main()+except (GateError, OSError, subprocess.SubprocessError) as error:+ print(f"BLOCKED: {error}", file=sys.stderr)+ raise SystemExit(1)+PYdiff --git a/scripts/ci/extract-release-archives.sh b/scripts/ci/extract-release-archives.shindex bc6e43056..0dbd8091c 100755--- a/scripts/ci/extract-release-archives.sh+++ b/scripts/ci/extract-release-archives.sh@@ -1,65 +1,856 @@#!/usr/bin/env bash-# Extract the release archives into a flat directory of scannable files.+# Validate the complete canonical release matrix and atomically build a+# content-deduplicated VirusTotal scan bundle.#-# Turns the per-platform artifacts (codebase-memory-mcp-<goos>-<goarch>.tar.gz /-# .zip, produced by the canonical package-release.sh) into one directory holding-# the actual executables, each renamed to its platform so a scan report names-# something a human can act on. The install scripts are copied in beside them:-# they ship in the release too, and a compromised installer matters as much as a-# compromised binary.+# Usage:+# extract-release-archives.sh <archive-dir> <output-dir> \+# [--expect-archives=N] [--expect-binaries=N] [--expect-packs=N] \+# [--expect-runtime-files=N]#-# Usage: extract-release-archives.sh <archive-dir> <output-dir>+# The output directory is published as one atomic bundle:+# objects/ one file per distinct byte sequence+# associations.tsv every archive, member and CBMUIPK asset -> scan object+# scan-set.tsv the exact path/hash/size set the VT action must return#-# Lives in scripts/ rather than inline in the workflow because the venue-parity-# contract requires it: a venue may provision, plumb artifacts, or call a-# canonical leg script, and this is leg logic. It also means the dry run and the-# release can extract identically instead of drifting apart in two YAML copies.+# The release archives themselves, their exact members, and the uncompressed+# HTML/JavaScript/CSS/etc payloads inside every CBMUIPK v1 pack are all covered.+# Identical bytes are uploaded once, but no shipped association is discarded.set -euo pipefail-ARCHIVE_DIR="${1:?extract-release-archives: missing <archive-dir>}"-OUT_DIR="${2:?extract-release-archives: missing <output-dir>}"-ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"--mkdir -p "$OUT_DIR"-shopt -s nullglob--# Counts BINARIES recovered from archives, deliberately not "files in OUT_DIR".-# The install scripts below are copied in unconditionally, so a whole-directory-# count is never zero and would have reported success on an empty input — a-# clean VirusTotal run over nothing, which is the precise false green this-# script exists to prevent. Caught by running it against an empty directory.-extracted=0--for archive in "$ARCHIVE_DIR"/*.tar.gz; do- name="$(basename "$archive" .tar.gz)"- tar -xzf "$archive" -C "$OUT_DIR" 2>/dev/null || true- if [ -f "$OUT_DIR/codebase-memory-mcp" ]; then- mv "$OUT_DIR/codebase-memory-mcp" "$OUT_DIR/${name}"- extracted=$((extracted + 1))- fi-done--for archive in "$ARCHIVE_DIR"/*.zip; do- name="$(basename "$archive" .zip)"- unzip -o "$archive" -d "$OUT_DIR" >/dev/null 2>&1 || true- if [ -f "$OUT_DIR/codebase-memory-mcp.exe" ]; then- mv "$OUT_DIR/codebase-memory-mcp.exe" "$OUT_DIR/${name}.exe"- extracted=$((extracted + 1))- fi-done--if [ "$extracted" -eq 0 ]; then- echo "FAIL: no binaries extracted from '$ARCHIVE_DIR' — a scan here would have"- echo " reported clean without examining a single byte"- ls -la "$ARCHIVE_DIR" 2>/dev/null || true- exit 1+if [ "$#" -lt 2 ]; then+ echo "Usage: $0 <archive-dir> <output-dir> [--expect-archives=N] [--expect-binaries=N] [--expect-packs=N] [--expect-runtime-files=N]" >&2+ exit 2fi-# Shipped alongside the binaries, so scanned alongside them: a compromised-# installer matters as much as a compromised executable.-cp "$ROOT/install.sh" "$OUT_DIR/" 2>/dev/null || true-cp "$ROOT/install.ps1" "$OUT_DIR/" 2>/dev/null || true+command -v python3 >/dev/null 2>&1 || {+ echo "FAIL: python3 is required to validate release archives" >&2+ exit 1+}++python3 - "$@" <<'PY'+from __future__ import annotations++import csv+import hashlib+import os+import pathlib+import re+import stat+import struct+import sys+import tarfile+import tempfile+import zipfile+from dataclasses import dataclass, field+from typing import BinaryIO, Dict, Iterable, List, Optional, Sequence, Tuple+++class ContractError(Exception):+ pass+++MIB = 1024 * 1024+GIB = 1024 * MIB+READ_CHUNK = MIB+MAX_ARCHIVE_BYTES = 512 * MIB+MAX_MEMBER_BYTES = 512 * MIB+MAX_TOTAL_MEMBER_BYTES = 8 * GIB+MAX_PACK_BYTES = 64 * MIB+PACK_HEADER_BYTES = 80+PACK_ENTRY_BYTES = 24+PACK_MAX_FILES = 1024+PACK_MAX_PATH_BYTES = 255++UNIX_TARGETS = (+ "linux-amd64",+ "linux-arm64",+ "darwin-amd64",+ "darwin-arm64",+ "linux-amd64-portable",+ "linux-arm64-portable",+)+WINDOWS_TARGETS = ("windows-amd64", "windows-arm64")+CANONICAL_ARCHIVES = frozenset(+ [+ f"codebase-memory-mcp{suffix}-{target}.tar.gz"+ for suffix in ("", "-ui")+ for target in UNIX_TARGETS+ ]+ + [+ f"codebase-memory-mcp{suffix}-{target}.zip"+ for suffix in ("", "-ui")+ for target in WINDOWS_TARGETS+ ]+)+PACK_NAME = re.compile(r"cbm-ui-([0-9a-f]{64})\.pack\Z")+SAFE_LABEL = re.compile(r"[^A-Za-z0-9._-]+")+SAFE_ASSET_PATH = re.compile(rb"\A[A-Za-z0-9._/-]+\Z")+COUNT_OPTIONS = {+ "--expect-archives": "archives",+ "--expect-binaries": "binaries",+ "--expect-packs": "packs",+ "--expect-runtime-files": "runtime_files",+}+MIME_BY_EXTENSION = {+ ".html": (1, "text/html"),+ ".js": (2, "application/javascript"),+ ".mjs": (2, "application/javascript"),+ ".css": (3, "text/css"),+ ".json": (4, "application/json"),+ ".svg": (5, "image/svg+xml"),+ ".png": (6, "image/png"),+ ".jpg": (7, "image/jpeg"),+ ".jpeg": (7, "image/jpeg"),+ ".webp": (8, "image/webp"),+ ".avif": (9, "image/avif"),+ ".ico": (10, "image/x-icon"),+ ".woff2": (11, "font/woff2"),+ ".woff": (12, "font/woff"),+ ".wasm": (13, "application/wasm"),+}+ASSOCIATION_FIELDS = (+ "association_type",+ "archive",+ "archive_sha256",+ "variant",+ "kind",+ "member",+ "asset_path",+ "mime",+ "scan_path",+ "object_sha256",+ "size",+)+SCAN_SET_FIELDS = (+ "scan_path",+ "sha256",+ "size",+ "association_count",+ "association_kinds",+)+++@dataclass+class ScanObject:+ path: pathlib.Path+ scan_path: str+ sha256: str+ size: int+ kinds: set[str] = field(default_factory=set)+ association_count: int = 0+++@dataclass(frozen=True)+class PackAsset:+ path: str+ mime: str+ offset: int+ size: int+++class SliceReader:+ def __init__(self, handle: BinaryIO, offset: int, size: int) -> None:+ self.handle = handle+ self.remaining = size+ handle.seek(offset)++ def read(self, length: int = -1) -> bytes:+ if self.remaining == 0:+ return b""+ wanted = self.remaining if length < 0 else min(length, self.remaining)+ data = self.handle.read(wanted)+ if not data:+ raise ContractError("UI pack payload ended before its declared asset length")+ self.remaining -= len(data)+ return data+++def files_equal(left: pathlib.Path, right: pathlib.Path) -> bool:+ """Exact comparison is mandatory even after the SHA-256+size grouping."""+ with left.open("rb") as left_handle, right.open("rb") as right_handle:+ while True:+ left_chunk = left_handle.read(READ_CHUNK)+ right_chunk = right_handle.read(READ_CHUNK)+ if left_chunk != right_chunk:+ return False+ if not left_chunk:+ return True+++def safe_object_label(label: str) -> str:+ cleaned = SAFE_LABEL.sub("-", pathlib.PurePosixPath(label).name).strip("-.")+ return (cleaned or "object")[:96]+++class ObjectStore:+ def __init__(self, directory: pathlib.Path) -> None:+ self.directory = directory+ self.directory.mkdir(mode=0o700)+ self.groups: Dict[Tuple[str, int], List[ScanObject]] = {}+ self.objects: List[ScanObject] = []+ self.candidate_index = 0++ def ingest_stream(+ self,+ source: BinaryIO,+ *,+ declared_size: int,+ ceiling: int,+ label: str,+ ) -> ScanObject:+ if declared_size < 0 or declared_size > ceiling:+ raise ContractError(+ f"object exceeds {ceiling} byte ceiling ({label}: {declared_size})"+ )+ self.candidate_index += 1+ candidate = self.directory / f".candidate-{self.candidate_index:06d}"+ digest = hashlib.sha256()+ total = 0+ try:+ with candidate.open("xb") as output:+ while True:+ chunk = source.read(min(READ_CHUNK, ceiling - total + 1))+ if not chunk:+ break+ total += len(chunk)+ if total > ceiling:+ raise ContractError(f"object exceeds {ceiling} byte ceiling ({label})")+ digest.update(chunk)+ output.write(chunk)+ output.flush()+ os.fsync(output.fileno())+ if total != declared_size:+ raise ContractError(+ f"object length mismatch ({label}: declared {declared_size}, read {total})"+ )++ sha256 = digest.hexdigest()+ group = self.groups.setdefault((sha256, total), [])+ for existing in group:+ if files_equal(candidate, existing.path):+ candidate.unlink()+ return existing++ collision = len(group) + 1+ collision_part = "" if collision == 1 else f"-collision-{collision}"+ name = (+ f"scan-{sha256}{collision_part}--{safe_object_label(label)}"+ )+ destination = self.directory / name+ if os.path.lexists(destination):+ raise ContractError(f"internal scan-object name collision: {name}")+ os.replace(candidate, destination)+ destination.chmod(0o600)+ result = ScanObject(+ path=destination,+ scan_path=f"objects/{name}",+ sha256=sha256,+ size=total,+ )+ group.append(result)+ self.objects.append(result)+ return result+ finally:+ if os.path.lexists(candidate):+ candidate.unlink()++ def ingest_path(self, path: pathlib.Path, *, ceiling: int, label: str) -> ScanObject:+ mode = path.lstat().st_mode+ if not stat.S_ISREG(mode):+ raise ContractError(f"scan input is not a regular file: {path}")+ size = path.stat().st_size+ with path.open("rb") as source:+ return self.ingest_stream(+ source,+ declared_size=size,+ ceiling=ceiling,+ label=label,+ )++ def ingest_slice(+ self,+ path: pathlib.Path,+ *,+ offset: int,+ size: int,+ label: str,+ ) -> ScanObject:+ with path.open("rb") as handle:+ source = SliceReader(handle, offset, size)+ result = self.ingest_stream(+ source,+ declared_size=size,+ ceiling=MAX_PACK_BYTES,+ label=label,+ )+ if source.remaining != 0:+ raise ContractError(f"UI pack asset was not read completely: {label}")+ return result+++def parse_arguments(+ argv: Sequence[str],+) -> Tuple[pathlib.Path, pathlib.Path, Dict[str, Optional[int]]]:+ archive_dir = pathlib.Path(argv[1]).absolute()+ output_dir = pathlib.Path(argv[2]).absolute()+ expected: Dict[str, Optional[int]] = {value: None for value in COUNT_OPTIONS.values()}+ seen: set[str] = set()+ for argument in argv[3:]:+ option, separator, raw_value = argument.partition("=")+ if not separator or option not in COUNT_OPTIONS:+ raise ContractError(f"unknown option: {argument}")+ key = COUNT_OPTIONS[option]+ if key in seen:+ raise ContractError(f"duplicate option: {option}")+ if not raw_value.isdigit():+ raise ContractError(f"{option} requires a non-negative integer")+ expected[key] = int(raw_value)+ seen.add(key)+ return archive_dir, output_dir, expected+++def validate_namespace(archive_name: str, names: Iterable[str]) -> Tuple[str, Dict[str, str]]:+ names_list = list(names)+ if len(names_list) != len(set(names_list)):+ duplicate = next(name for name in names_list if names_list.count(name) > 1)+ raise ContractError(f"duplicate archive member in {archive_name}: {duplicate}")+ windows = archive_name.endswith(".zip")+ variant = "ui" if archive_name.startswith("codebase-memory-mcp-ui-") else "standard"+ binary = "codebase-memory-mcp.exe" if windows else "codebase-memory-mcp"+ installer = "install.ps1" if windows else "install.sh"+ fixed = {+ binary: "binary",+ "cbm-integrations.json": "runtime",+ "LICENSE": "runtime",+ installer: "runtime",+ "THIRD_PARTY_NOTICES.md": "runtime",+ }+ name_set = set(names_list)+ extras = name_set - set(fixed)+ if variant == "ui":+ invalid = sorted(name for name in extras if PACK_NAME.fullmatch(name) is None)+ if invalid:+ raise ContractError(f"unexpected archive member in {archive_name}: {invalid[0]}")+ if len(extras) != 1:+ raise ContractError(+ f"UI archive must contain exactly one UI pack in {archive_name}; got {len(extras)}"+ )+ if len(name_set) != 6 or not set(fixed).issubset(name_set):+ missing = sorted(set(fixed) - name_set)+ raise ContractError(+ f"member namespace mismatch in {archive_name}: expected exactly 6 root files; missing={missing}"+ )+ kinds = dict(fixed)+ kinds[next(iter(extras))] = "pack"+ return variant, kinds+ if extras:+ raise ContractError(f"unexpected archive member in {archive_name}: {sorted(extras)[0]}")+ if len(name_set) != 5 or name_set != set(fixed):+ missing = sorted(set(fixed) - name_set)+ raise ContractError(+ f"member namespace mismatch in {archive_name}: expected exactly 5 root files; missing={missing}"+ )+ return variant, fixed+++def valid_asset_path(raw: bytes) -> bool:+ if (+ len(raw) < 2+ or len(raw) > PACK_MAX_PATH_BYTES+ or not SAFE_ASSET_PATH.fullmatch(raw)+ or not raw.startswith(b"/")+ or raw.endswith(b"/")+ or b"//" in raw+ ):+ return False+ parts = raw[1:].split(b"/")+ if any(part in (b"", b".", b"..") for part in parts):+ return False+ return raw == b"/index.html" or raw.startswith(b"/assets/")+++def parse_pack_assets(path: pathlib.Path) -> List[PackAsset]:+ size = path.stat().st_size+ if size < PACK_HEADER_BYTES or size > MAX_PACK_BYTES:+ raise ContractError(f"CBMUIPK size is outside bounds: {size}")+ with path.open("rb") as handle:+ header = handle.read(PACK_HEADER_BYTES)+ if len(header) != PACK_HEADER_BYTES:+ raise ContractError("CBMUIPK header is truncated")+ try:+ (+ magic,+ version,+ header_bytes,+ flags,+ count,+ entry_bytes,+ index_offset,+ index_size,+ paths_offset,+ paths_size,+ payload_offset,+ payload_size,+ total_size,+ ) = struct.unpack("<8sHHIIIQQQQQQQ", header)+ except struct.error as error:+ raise ContractError(f"CBMUIPK header is malformed: {error}") from error+ if (+ magic != b"CBMUIPK\0"+ or version != 1+ or header_bytes != PACK_HEADER_BYTES+ or flags != 0+ or count < 1+ or count > PACK_MAX_FILES+ or entry_bytes != PACK_ENTRY_BYTES+ or index_offset != PACK_HEADER_BYTES+ or index_size != count * PACK_ENTRY_BYTES+ or paths_offset != index_offset + index_size+ or paths_size > count * PACK_MAX_PATH_BYTES+ or payload_offset != paths_offset + paths_size+ or total_size != payload_offset + payload_size+ or total_size != size+ ):+ raise ContractError("CBMUIPK header/offset contract failed")+ handle.seek(index_offset)+ index = handle.read(index_size)+ paths = handle.read(paths_size)+ if len(index) != index_size or len(paths) != paths_size:+ raise ContractError("CBMUIPK index or path table is truncated")++ assets: List[PackAsset] = []+ expected_path_offset = 0+ expected_data_offset = 0+ previous_path: Optional[bytes] = None+ has_index = False+ for item in range(count):+ entry = struct.unpack_from("<IHBBQQ", index, item * PACK_ENTRY_BYTES)+ path_offset, path_length, mime_id, cache_id, data_offset, data_length = entry+ if (+ path_offset != expected_path_offset+ or path_length == 0+ or path_length > paths_size - expected_path_offset+ or data_offset != expected_data_offset+ or data_length == 0+ or data_length > payload_size - expected_data_offset+ ):+ raise ContractError("CBMUIPK entry bounds/contiguity contract failed")+ raw_path = paths[path_offset : path_offset + path_length]+ if not valid_asset_path(raw_path) or (previous_path is not None and previous_path >= raw_path):+ raise ContractError("CBMUIPK asset path is invalid, duplicate or unsorted")+ try:+ asset_path = raw_path.decode("ascii")+ except UnicodeDecodeError as error:+ raise ContractError("CBMUIPK asset path is not ASCII") from error+ extension = pathlib.PurePosixPath(asset_path).suffix+ mapping = MIME_BY_EXTENSION.get(extension)+ if mapping is None or mime_id != mapping[0]:+ raise ContractError(f"CBMUIPK MIME/path contract failed: {asset_path}")+ is_index = asset_path == "/index.html"+ if cache_id != (1 if is_index else 2) or (is_index and has_index):+ raise ContractError(f"CBMUIPK cache/index contract failed: {asset_path}")+ has_index = has_index or is_index+ assets.append(+ PackAsset(+ path=asset_path,+ mime=mapping[1],+ offset=payload_offset + data_offset,+ size=data_length,+ )+ )+ previous_path = raw_path+ expected_path_offset += path_length+ expected_data_offset += data_length+ if not has_index or expected_path_offset != paths_size or expected_data_offset != payload_size:+ raise ContractError("CBMUIPK tables do not cover exactly one complete payload")+ return assets+++def add_association(+ rows: List[Dict[str, object]],+ scan_object: ScanObject,+ *,+ association_type: str,+ archive: str,+ archive_sha256: str,+ variant: str,+ kind: str,+ member: str = "",+ asset_path: str = "",+ mime: str = "",+) -> None:+ scan_object.association_count += 1+ scan_object.kinds.add(kind)+ rows.append(+ {+ "association_type": association_type,+ "archive": archive,+ "archive_sha256": archive_sha256,+ "variant": variant,+ "kind": kind,+ "member": member,+ "asset_path": asset_path,+ "mime": mime,+ "scan_path": scan_object.scan_path,+ "object_sha256": scan_object.sha256,+ "size": scan_object.size,+ }+ )+++def validate_member_metadata(archive_name: str, names_and_sizes: Iterable[Tuple[str, int]]) -> int:+ total = 0+ for name, size in names_and_sizes:+ if not name or "\t" in name or "\n" in name or "\r" in name:+ raise ContractError(f"invalid archive member name in {archive_name}")+ if size < 0 or size > MAX_MEMBER_BYTES:+ raise ContractError(+ f"archive member exceeds {MAX_MEMBER_BYTES} byte ceiling in {archive_name}: {name}"+ )+ total += size+ if total > MAX_TOTAL_MEMBER_BYTES:+ raise ContractError("release matrix exceeds total uncompressed byte ceiling")+ return total+++def process_member(+ *,+ store: ObjectStore,+ rows: List[Dict[str, object]],+ source: BinaryIO,+ size: int,+ member: str,+ kind: str,+ archive_name: str,+ archive_sha256: str,+ variant: str,+) -> None:+ scan_object = store.ingest_stream(+ source,+ declared_size=size,+ ceiling=MAX_MEMBER_BYTES,+ label=member,+ )+ if kind == "pack":+ match = PACK_NAME.fullmatch(member)+ if match is None or scan_object.sha256 != match.group(1):+ raise ContractError(+ f"UI pack digest does not match its filename in {archive_name}: {member}"+ )+ add_association(+ rows,+ scan_object,+ association_type="member",+ archive=archive_name,+ archive_sha256=archive_sha256,+ variant=variant,+ kind=kind,+ member=member,+ )+ if kind != "pack":+ return+ for asset in parse_pack_assets(scan_object.path):+ asset_object = store.ingest_slice(+ scan_object.path,+ offset=asset.offset,+ size=asset.size,+ label=asset.path,+ )+ add_association(+ rows,+ asset_object,+ association_type="pack_asset",+ archive=archive_name,+ archive_sha256=archive_sha256,+ variant=variant,+ kind="ui_asset",+ member=member,+ asset_path=asset.path,+ mime=asset.mime,+ )+++def process_tar(+ path: pathlib.Path,+ *,+ archive_name: str,+ store: ObjectStore,+ rows: List[Dict[str, object]],+ archive_sha256: str,+ remaining_member_bytes: int,+) -> Tuple[str, Dict[str, str], int]:+ with tarfile.open(path, "r:gz") as archive:+ infos = archive.getmembers()+ seen: set[str] = set()+ for info in infos:+ if info.name in seen:+ raise ContractError(f"duplicate archive member in {archive_name}: {info.name}")+ seen.add(info.name)+ if not info.isfile():+ raise ContractError(f"non-regular archive member in {archive_name}: {info.name}")+ total = validate_member_metadata(archive_name, ((info.name, info.size) for info in infos))+ if total > remaining_member_bytes:+ raise ContractError("release matrix exceeds total uncompressed byte ceiling")+ variant, kinds = validate_namespace(archive_name, [info.name for info in infos])+ for info in sorted(infos, key=lambda item: item.name):+ source = archive.extractfile(info)+ if source is None:+ raise ContractError(f"could not read archive member in {archive_name}: {info.name}")+ with source:+ process_member(+ store=store,+ rows=rows,+ source=source,+ size=info.size,+ member=info.name,+ kind=kinds[info.name],+ archive_name=archive_name,+ archive_sha256=archive_sha256,+ variant=variant,+ )+ return variant, kinds, total+++def process_zip(+ path: pathlib.Path,+ *,+ archive_name: str,+ store: ObjectStore,+ rows: List[Dict[str, object]],+ archive_sha256: str,+ remaining_member_bytes: int,+) -> Tuple[str, Dict[str, str], int]:+ with zipfile.ZipFile(path, "r") as archive:+ infos = archive.infolist()+ seen: set[str] = set()+ for info in infos:+ name = info.filename+ if name in seen:+ raise ContractError(f"duplicate archive member in {archive_name}: {name}")+ seen.add(name)+ unix_mode = (info.external_attr >> 16) & 0xFFFF+ file_type = stat.S_IFMT(unix_mode)+ if info.is_dir() or name.endswith("/") or file_type not in (0, stat.S_IFREG):+ raise ContractError(f"non-regular archive member in {archive_name}: {name}")+ if info.flag_bits & 0x1:+ raise ContractError(f"encrypted archive member in {archive_name}: {name}")+ total = validate_member_metadata(archive_name, ((info.filename, info.file_size) for info in infos))+ if total > remaining_member_bytes:+ raise ContractError("release matrix exceeds total uncompressed byte ceiling")+ variant, kinds = validate_namespace(archive_name, [info.filename for info in infos])+ for info in sorted(infos, key=lambda item: item.filename):+ with archive.open(info, "r") as source:+ process_member(+ store=store,+ rows=rows,+ source=source,+ size=info.file_size,+ member=info.filename,+ kind=kinds[info.filename],+ archive_name=archive_name,+ archive_sha256=archive_sha256,+ variant=variant,+ )+ return variant, kinds, total+++def write_tsv(+ path: pathlib.Path,+ *,+ marker: str,+ metadata: Iterable[Tuple[str, int]],+ fields: Sequence[str],+ rows: Iterable[Dict[str, object]],+) -> None:+ with path.open("x", encoding="utf-8", newline="") as handle:+ handle.write(f"# {marker}\n")+ for key, value in metadata:+ handle.write(f"# {key}={value}\n")+ writer = csv.DictWriter(handle, fieldnames=fields, delimiter="\t", lineterminator="\n")+ writer.writeheader()+ writer.writerows(rows)+ handle.flush()+ os.fsync(handle.fileno())+++def main(argv: Sequence[str]) -> None:+ archive_dir, output_dir, expected = parse_arguments(argv)+ if not archive_dir.is_dir() or archive_dir.is_symlink():+ raise ContractError(f"archive directory is not a regular directory: {archive_dir}")+ if output_dir.name in ("", ".", ".."):+ raise ContractError(f"unsafe output directory: {output_dir}")+ if os.path.lexists(output_dir):+ if output_dir.is_symlink() or not output_dir.is_dir():+ raise ContractError(f"output path is not a regular directory: {output_dir}")+ if any(output_dir.iterdir()):+ raise ContractError(f"output directory must be empty: {output_dir}")++ archive_paths = sorted(archive_dir.iterdir(), key=lambda candidate: candidate.name)+ actual_names = {path.name for path in archive_paths}+ if actual_names != CANONICAL_ARCHIVES or len(archive_paths) != len(CANONICAL_ARCHIVES):+ missing = sorted(CANONICAL_ARCHIVES - actual_names)+ unexpected = sorted(actual_names - CANONICAL_ARCHIVES)+ raise ContractError(+ f"archive namespace mismatch: expected exact canonical 16; missing={missing}, unexpected={unexpected}"+ )+ for path in archive_paths:+ mode = path.lstat().st_mode+ if not stat.S_ISREG(mode):+ raise ContractError(f"archive is not a regular file: {path.name}")+ if path.stat().st_size > MAX_ARCHIVE_BYTES:+ raise ContractError(+ f"archive exceeds {MAX_ARCHIVE_BYTES} byte ceiling: {path.name}"+ )++ output_dir.parent.mkdir(parents=True, exist_ok=True)+ rows: List[Dict[str, object]] = []+ counts = {+ "archives": 0,+ "binaries": 0,+ "packs": 0,+ "runtime_files": 0,+ "pack_assets": 0,+ "associations": 0,+ "scan_objects": 0,+ }+ total_members = 0++ with tempfile.TemporaryDirectory(prefix=".cbm-release-scan-", dir=str(output_dir.parent)) as temporary:+ staged_output = pathlib.Path(temporary) / "bundle"+ staged_output.mkdir(mode=0o700)+ store = ObjectStore(staged_output / "objects")+ for archive_path in archive_paths:+ archive_name = archive_path.name+ variant = "ui" if archive_name.startswith("codebase-memory-mcp-ui-") else "standard"+ archive_object = store.ingest_path(+ archive_path,+ ceiling=MAX_ARCHIVE_BYTES,+ label=archive_name,+ )+ archive_sha256 = archive_object.sha256+ add_association(+ rows,+ archive_object,+ association_type="archive",+ archive=archive_name,+ archive_sha256=archive_sha256,+ variant=variant,+ kind="archive",+ )+ _, kinds, member_total = (+ process_tar(+ archive_object.path,+ archive_name=archive_name,+ store=store,+ rows=rows,+ archive_sha256=archive_sha256,+ remaining_member_bytes=MAX_TOTAL_MEMBER_BYTES - total_members,+ )+ if archive_name.endswith(".tar.gz")+ else process_zip(+ archive_object.path,+ archive_name=archive_name,+ store=store,+ rows=rows,+ archive_sha256=archive_sha256,+ remaining_member_bytes=MAX_TOTAL_MEMBER_BYTES - total_members,+ )+ )+ total_members += member_total+ if total_members > MAX_TOTAL_MEMBER_BYTES:+ raise ContractError("release matrix exceeds total uncompressed byte ceiling")+ counts["archives"] += 1+ counts["binaries"] += sum(kind == "binary" for kind in kinds.values())+ counts["packs"] += sum(kind == "pack" for kind in kinds.values())+ counts["runtime_files"] += sum(kind == "runtime" for kind in kinds.values())++ counts["pack_assets"] = sum(row["association_type"] == "pack_asset" for row in rows)+ counts["associations"] = len(rows)+ counts["scan_objects"] = len(store.objects)+ for key in ("archives", "binaries", "packs", "runtime_files"):+ wanted = expected[key]+ if wanted is not None and counts[key] != wanted:+ display = key.replace("_files", " files")+ raise ContractError(+ f"count contract failed: {display} expected {wanted}, got {counts[key]}"+ )++ rows.sort(+ key=lambda row: (+ str(row["archive"]),+ {"archive": 0, "member": 1, "pack_asset": 2}[str(row["association_type"])],+ str(row["member"]),+ str(row["asset_path"]),+ )+ )+ metadata_order = (+ "archives",+ "binaries",+ "packs",+ "runtime_files",+ "pack_assets",+ "associations",+ "scan_objects",+ )+ write_tsv(+ staged_output / "associations.tsv",+ marker="cbm-release-scan-associations-v2",+ metadata=((key, counts[key]) for key in metadata_order),+ fields=ASSOCIATION_FIELDS,+ rows=rows,+ )+ scan_rows = [+ {+ "scan_path": item.scan_path,+ "sha256": item.sha256,+ "size": item.size,+ "association_count": item.association_count,+ "association_kinds": ",".join(sorted(item.kinds)),+ }+ for item in sorted(store.objects, key=lambda item: item.scan_path)+ ]+ write_tsv(+ staged_output / "scan-set.tsv",+ marker="cbm-release-scan-set-v1",+ metadata=((key, counts[key]) for key in ("scan_objects", "associations")),+ fields=SCAN_SET_FIELDS,+ rows=scan_rows,+ )+ for item in store.objects:+ item.path.chmod(0o644)++ # The objects and both manifests become visible together. A rejected+ # archive matrix can therefore never leave a partial set for the action.+ if output_dir.exists():+ if any(output_dir.iterdir()):+ raise ContractError(f"output directory became non-empty: {output_dir}")+ output_dir.rmdir()+ os.replace(staged_output, output_dir)++ print(+ f"validated exact {counts['archives']}-archive matrix: "+ f"{counts['binaries']} binaries, {counts['packs']} UI packs, "+ f"{counts['runtime_files']} runtime files and {counts['pack_assets']} pack assets"+ )+ print(+ f"scan bundle: {counts['scan_objects']} distinct byte objects cover "+ f"{counts['associations']} archive/member/asset associations"+ )+ print(f"associations: {output_dir / 'associations.tsv'}")+ print(f"expected scan set: {output_dir / 'scan-set.tsv'}")+-ls -la "$OUT_DIR"-total="$(find "$OUT_DIR" -maxdepth 1 -type f | wc -l | tr -d ' ')"-echo "extracted $extracted binarie(s); $total file(s) queued for scanning"+try:+ main(sys.argv)+except (+ ContractError,+ OSError,+ OverflowError,+ struct.error,+ tarfile.TarError,+ zipfile.BadZipFile,+ zipfile.LargeZipFile,+) as error:+ print(f"FAIL: {error}", file=sys.stderr)+ raise SystemExit(1)+PYdiff --git a/scripts/ci/publish-vt-evidence.sh b/scripts/ci/publish-vt-evidence.shnew file mode 100644index 000000000..3369855a3--- /dev/null+++ b/scripts/ci/publish-vt-evidence.sh@@ -0,0 +1,63 @@+#!/usr/bin/env bash+# Publish the complete, already-gated VirusTotal evidence as durable release+# assets. Workflow artifacts are useful diagnostics but expire and may require+# repository access; these fixed-name files remain attached to the public+# release whose exact objects they describe.+set -euo pipefail++: "${GH_TOKEN:?publish-vt-evidence: GH_TOKEN is required}"+: "${VERSION:?publish-vt-evidence: VERSION is required}"+: "${GITHUB_REPOSITORY:?publish-vt-evidence: GITHUB_REPOSITORY is required}"++VT_ASSOCIATIONS="${VT_ASSOCIATIONS:-binaries/associations.tsv}"+VT_EXPECTED_SCAN_SET="${VT_EXPECTED_SCAN_SET:-binaries/scan-set.tsv}"+VT_RESULTS_PATH="${VT_RESULTS_PATH:-binaries/vt-results.tsv}"+WORK="$(mktemp -d "${TMPDIR:-/tmp}/cbm-vt-public.XXXXXX")"+trap 'rm -rf "$WORK"' EXIT++publish_copy() {+ local source="$1" marker="$2" destination="$3" first_line size+ if [ ! -f "$source" ] || [ -L "$source" ]; then+ echo "publish-vt-evidence: missing or unsafe evidence file: $source" >&2+ exit 1+ fi+ size=$(wc -c < "$source" | tr -d '[:space:]')+ case "$size" in+ ''|*[!0-9]*) echo "publish-vt-evidence: cannot measure evidence file: $source" >&2; exit 1 ;;+ esac+ if [ "$size" -le 0 ] || [ "$size" -gt 16777216 ]; then+ echo "publish-vt-evidence: empty or oversized evidence file: $source" >&2+ exit 1+ fi+ IFS= read -r first_line < "$source" || true+ if [ "$first_line" != "# $marker" ]; then+ echo "publish-vt-evidence: wrong evidence marker in $source" >&2+ exit 1+ fi+ cp "$source" "$WORK/$destination"+ chmod 0644 "$WORK/$destination"+}++publish_copy "$VT_ASSOCIATIONS" cbm-release-scan-associations-v2 virustotal-associations.tsv+publish_copy "$VT_EXPECTED_SCAN_SET" cbm-release-scan-set-v1 virustotal-scan-set.tsv+publish_copy "$VT_RESULTS_PATH" cbm-virustotal-results-v1 virustotal-results.tsv++for name in virustotal-associations.tsv virustotal-results.tsv virustotal-scan-set.tsv; do+ if command -v sha256sum >/dev/null 2>&1; then+ digest=$(sha256sum "$WORK/$name" | awk '{print $1}')+ elif command -v shasum >/dev/null 2>&1; then+ digest=$(shasum -a 256 "$WORK/$name" | awk '{print $1}')+ else+ echo "publish-vt-evidence: no SHA-256 tool is available" >&2+ exit 1+ fi+ printf '%s %s\n' "$digest" "$name" >> "$WORK/virustotal-evidence-checksums.txt"+done+chmod 0644 "$WORK/virustotal-evidence-checksums.txt"++gh release upload "$VERSION" \+ "$WORK/virustotal-associations.tsv" \+ "$WORK/virustotal-scan-set.tsv" \+ "$WORK/virustotal-results.tsv" \+ "$WORK/virustotal-evidence-checksums.txt" \+ --clobber --repo "$GITHUB_REPOSITORY"diff --git a/scripts/ci/smoke-artifact.sh b/scripts/ci/smoke-artifact.shindex 539a70415..b019aa032 100755--- a/scripts/ci/smoke-artifact.sh+++ b/scripts/ci/smoke-artifact.sh@@ -26,7 +26,7 @@ artifact through the canonical wrapper, exactly like the release venue:windows: test-infrastructure/vm/vm-smoke.sh with CBM_SMOKE_ARTIFACT_DIR(run inside the VM/CI msys2 shell)- --variant ui builds --with-ui and smokes the ui archive (Phase 15 embedded+ --variant ui builds --with-ui and smokes the ui archive (Phase 15 externalassets become mandatory — a standard binary cannot pass a ui run).Make passthrough (VAR=VAL): CC= CXX= STATIC=1 ... forwarded to build steps.@@ -104,8 +104,8 @@ mkdir -p "$EXTRACT_DIR"if [ "$GOOS" = "windows" ]; thenunzip -q -o "$WORK_DIR/$NAME.zip" -d "$EXTRACT_DIR"test -s "$EXTRACT_DIR/codebase-memory-mcp.exe"- # ONE binary per platform: a payload sibling means the AV-flagged launcher- # stub came back.+ # ONE executable per runtime set: a payload sibling means the removed+ # launcher split came back.test ! -e "$EXTRACT_DIR/codebase-memory-mcp.payload.exe"echo "=== smoke-artifact: smoking EXTRACTED $NAME.zip via vm-smoke.sh ==="SMOKE_ARCH="$GOARCH" SMOKE_VARIANT="$VARIANT" \diff --git a/scripts/ci/test-package-wrappers.sh b/scripts/ci/test-package-wrappers.shnew file mode 100644index 000000000..11c8d7643--- /dev/null+++ b/scripts/ci/test-package-wrappers.sh@@ -0,0 +1,73 @@+#!/usr/bin/env bash+# Gate the three package-manager wrappers against the host's real filesystem+# and process-lock semantics. CI runs this once on Unix and once on Windows.++set -euo pipefail++ROOT="$(cd "$(dirname "$0")/../.." && pwd)"++usage() {+ cat <<'EOF'+Usage: scripts/ci/test-package-wrappers.sh++Run the Go, npm, and PyPI wrapper suites on the current host. The caller must+provide the Go version declared by pkg/go/go.mod, Node.js >=18, and Python >=3.8.+The Go toolchain is kept local so this test never hides a missing provisioned+toolchain behind an implicit download.+EOF+}++case "${1:-}" in+-h | --help)+ usage+ exit 0+ ;;+"") ;;+*)+ echo "test-package-wrappers.sh: unexpected argument '$1'. Please consult --help." >&2+ exit 2+ ;;+esac++for tool in go npm; do+ if ! command -v "$tool" >/dev/null 2>&1; then+ echo "test-package-wrappers.sh: required tool is missing: $tool" >&2+ exit 2+ fi+done++PYTHON=()+if command -v python3 >/dev/null 2>&1; then+ PYTHON=(python3)+elif command -v python >/dev/null 2>&1; then+ PYTHON=(python)+elif command -v py >/dev/null 2>&1; then+ PYTHON=(py -3)+else+ echo "test-package-wrappers.sh: Python 3 is required" >&2+ exit 2+fi+if ! "${PYTHON[@]}" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 8) else 1)'; then+ echo "test-package-wrappers.sh: Python >=3.8 is required" >&2+ exit 2+fi++echo "=== Package wrapper: Go ==="+(+ cd "$ROOT/pkg/go"+ GOTOOLCHAIN=local go test ./...+)++echo "=== Package wrapper: npm ==="+(+ cd "$ROOT/pkg/npm"+ npm test+)++echo "=== Package wrapper: PyPI ==="+(+ cd "$ROOT/pkg/pypi"+ "${PYTHON[@]}" -m unittest discover -s tests -p 'test_*.py'+)++echo "=== All package wrapper suites passed ==="diff --git a/scripts/clean.sh b/scripts/clean.shindex 882e88c53..4555dca68 100755--- a/scripts/clean.sh+++ b/scripts/clean.sh@@ -30,9 +30,6 @@ rm -rf "$ROOT/graph-ui/node_modules"# Root-level node artifacts (if any)rm -rf "$ROOT/node_modules"-# Generated embedded assets (regenerated by embed-frontend.sh)-rm -f "$ROOT/src/ui/embedded_assets.c"-# Leftover test fixture dirs (C test suite sometimes creates these in CWD)find "$ROOT" -maxdepth 1 -type d \( -name 'cbm_*' -o -name 'cli-*' \) -exec rm -rf {} + 2>/dev/null || truediff --git a/scripts/embed-frontend.sh b/scripts/embed-frontend.shdeleted file mode 100755index 0b7b87309..000000000--- a/scripts/embed-frontend.sh+++ /dev/null@@ -1,194 +0,0 @@-#!/usr/bin/env bash-# embed-frontend.sh — Convert built frontend assets into linkable object files.-#-# Usage: scripts/embed-frontend.sh <dist_dir> <output_dir>-#-# For each file in dist_dir, creates:-# 1. An object file via `ld -r -b binary` (raw bytes, zero bloat)-# 2. A generated embedded_assets.c with a lookup table-#-# Symbols created per file: _binary_<mangled_name>_start, _binary_<mangled_name>_end-# On macOS, these get a leading underscore: __binary_<mangled_name>_start--set -euo pipefail--DIST_DIR="${1:?Usage: embed-frontend.sh <dist_dir> <output_dir>}"-OUTPUT_DIR="${2:?Usage: embed-frontend.sh <dist_dir> <output_dir>}"--# Clean old embedded objects (asset hashes change on each build)-rm -rf "$OUTPUT_DIR"-mkdir -p "$OUTPUT_DIR"--# Detect platform — Linux uses ld -r -b binary, everything else uses xxd+cc-IS_LINUX=false-if [[ "$(uname -s)" == "Linux" ]] && ! [[ "$(uname -s)" =~ MINGW|MSYS ]]; then- IS_LINUX=true-fi--# Content-type detection-content_type_for() {- local f="$1"- case "$f" in- *.html) echo "text/html" ;;- *.js) echo "application/javascript" ;;- *.css) echo "text/css" ;;- *.json) echo "application/json" ;;- *.svg) echo "image/svg+xml" ;;- *.png) echo "image/png" ;;- *.ico) echo "image/x-icon" ;;- *.woff2) echo "font/woff2" ;;- *.woff) echo "font/woff" ;;- *.map) echo "application/json" ;;- *) echo "application/octet-stream" ;;- esac-}--# Mangle filename to valid C symbol: replace non-alnum with _-mangle() {- echo "$1" | sed 's/[^a-zA-Z0-9]/_/g'-}--# Collect all files-FILES=()-while IFS= read -r -d '' file; do- FILES+=("$file")-done < <(find "$DIST_DIR" -type f -print0 | sort -z)--if [[ ${#FILES[@]} -eq 0 ]]; then- echo "Error: no files found in $DIST_DIR" >&2- exit 1-fi--echo "Embedding ${#FILES[@]} files from $DIST_DIR"--# Generate object files-OBJ_FILES=()-for file in "${FILES[@]}"; do- rel="${file#$DIST_DIR/}"- mangled=$(mangle "$rel")- obj="$OUTPUT_DIR/embed_${mangled}.o"-- if $IS_LINUX; then- # Linux: ld -r -b binary (zero bloat, ELF only)- abs_obj="$(cd "$(dirname "$0")/.." && pwd)/$obj"- (cd "$DIST_DIR" && ld -r -b binary -o "$abs_obj" "$rel")- else- # macOS/Windows/MSYS2: generate C byte array + cc (no xxd dependency)- local_c="$OUTPUT_DIR/embed_${mangled}.c"- local_sym="_binary_${mangled}"-- echo "/* Generated from $rel */" > "$local_c"- echo "const unsigned char ${local_sym}_data[] = {" >> "$local_c"- # Use od (POSIX) to generate hex bytes — works everywhere without xxd/vim- od -An -tx1 -v < "$file" | tr -s ' ' '\n' | grep -v '^$' | sed 's/^/0x/; s/$/,/' | paste -sd' ' - | fold -s -w 76 | sed 's/^/ /' >> "$local_c"- echo "};" >> "$local_c"- echo "const unsigned int ${local_sym}_size = sizeof(${local_sym}_data);" >> "$local_c"-- ${CC:-cc} -c -O2 -o "$obj" "$local_c"- rm -f "$local_c"- fi-- OBJ_FILES+=("$obj")- echo " $rel -> $obj"-done--# Generate embedded_assets.c-ASSETS_C="src/ui/embedded_assets.c"-cat > "$ASSETS_C" <<'HEADER'-/*- * embedded_assets.c — Generated file mapping URL paths to embedded bytes.- * DO NOT EDIT — regenerated by scripts/embed-frontend.sh- */-#include "ui/embedded_assets.h"-#include <string.h>--HEADER--# Declare extern symbols-for file in "${FILES[@]}"; do- rel="${file#$DIST_DIR/}"- mangled=$(mangle "$rel")- sym="_binary_${mangled}"-- if ! $IS_LINUX; then- echo "extern const unsigned char ${sym}_data[];" >> "$ASSETS_C"- echo "extern const unsigned int ${sym}_size;" >> "$ASSETS_C"- else- echo "extern const unsigned char ${sym}_start[];" >> "$ASSETS_C"- echo "extern const unsigned char ${sym}_end[];" >> "$ASSETS_C"- fi-done--echo "" >> "$ASSETS_C"-echo "cbm_embedded_file_t CBM_EMBEDDED_FILES[] = {" >> "$ASSETS_C"--for file in "${FILES[@]}"; do- rel="${file#$DIST_DIR/}"- mangled=$(mangle "$rel")- sym="_binary_${mangled}"- ct=$(content_type_for "$rel")-- # URL path: /index.html for root, /assets/... for assets- url_path="/$rel"-- if ! $IS_LINUX; then- echo " {\"$url_path\", ${sym}_data, 0, \"$ct\"}," >> "$ASSETS_C"- else- echo " {\"$url_path\", ${sym}_start, 0, \"$ct\"}," >> "$ASSETS_C"- fi-done--echo "};" >> "$ASSETS_C"-echo "const int CBM_EMBEDDED_FILE_COUNT = ${#FILES[@]};" >> "$ASSETS_C"--# Generate size fixup-if $IS_LINUX; then- # Linux: compute size from start/end pointers (ld -r -b binary symbols)- cat >> "$ASSETS_C" <<'SIZEINIT'--static void __attribute__((constructor)) init_embedded_sizes(void) {- cbm_embedded_file_t *files = CBM_EMBEDDED_FILES;-SIZEINIT-- for i in "${!FILES[@]}"; do- rel="${FILES[$i]#$DIST_DIR/}"- mangled=$(mangle "$rel")- sym="_binary_${mangled}"- echo " files[$i].size = (unsigned int)(${sym}_end - ${sym}_start);" >> "$ASSETS_C"- done-- echo "}" >> "$ASSETS_C"-else- # macOS/Windows: use explicit _size vars from xxd-generated C arrays- cat >> "$ASSETS_C" <<'SIZEINIT'--static void __attribute__((constructor)) init_embedded_sizes(void) {- cbm_embedded_file_t *files = CBM_EMBEDDED_FILES;-SIZEINIT-- for i in "${!FILES[@]}"; do- rel="${FILES[$i]#$DIST_DIR/}"- mangled=$(mangle "$rel")- sym="_binary_${mangled}"- echo " files[$i].size = ${sym}_size;" >> "$ASSETS_C"- done-- echo "}" >> "$ASSETS_C"-fi--# Add lookup function-cat >> "$ASSETS_C" <<'LOOKUP'--const cbm_embedded_file_t *cbm_embedded_lookup(const char *path) {- for (int i = 0; i < CBM_EMBEDDED_FILE_COUNT; i++) {- if (strcmp(CBM_EMBEDDED_FILES[i].path, path) == 0) {- return &CBM_EMBEDDED_FILES[i];- }- }- return NULL;-}-LOOKUP--echo "Generated $ASSETS_C with ${#FILES[@]} embedded files"-echo "Object files in $OUTPUT_DIR:"-printf ' %s\n' "${OBJ_FILES[@]}"diff --git a/scripts/gen-third-party-notices.sh b/scripts/gen-third-party-notices.shindex 08741c686..3ae9585e8 100755--- a/scripts/gen-third-party-notices.sh+++ b/scripts/gen-third-party-notices.sh@@ -43,8 +43,9 @@ mkdir -p "$(dirname "$OUT")"done# With-ui packaging path: node_modules exists (make frontend ran npm ci),- # so append the license texts of the npm packages compiled into the UI- # bundle. Standard binaries carry no bundle — the section is skipped.+ # so append the license texts of the npm packages compiled into the+ # external UI pack. Standard archives carry no pack — the section is+ # skipped.if [ -d "$ROOT/graph-ui/node_modules" ]; thenechoecho "---"diff --git a/scripts/gen-ui-licenses.py b/scripts/gen-ui-licenses.pyindex 6b62944db..97fea571e 100755--- a/scripts/gen-ui-licenses.py+++ b/scripts/gen-ui-licenses.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Emit a markdown license appendix for the embedded graph-UI bundle.+"""Emit a markdown license appendix for the external graph-UI asset pack.Usage: gen-ui-licenses.py <graph-ui-dir>@@ -78,10 +78,10 @@ def main():excluded = set()collect(ui_dir, tree.get("dependencies"), pkgs, excluded)- print("## Embedded Graph UI — bundled npm packages")+ print("## External Graph UI asset pack — bundled npm packages")print()- print("The `-ui` binaries embed a compiled frontend bundle. The packages")- print("below are its production dependency tree; their license texts are")+ print("The `-ui` archives ship a compiled frontend asset pack beside the binary.")+ print("The packages below are its production dependency tree; license texts are")print("reproduced verbatim from the packages as installed at build time.")print()diff --git a/scripts/license-gate.sh b/scripts/license-gate.shindex 723e5826b..afc98f17c 100755--- a/scripts/license-gate.sh+++ b/scripts/license-gate.sh@@ -108,9 +108,9 @@ scancode --license --quiet --processes 2 --json-pp "$STAGE/scan.json" "$STAGE/trpython3 scripts/license-gate-check.py "$STAGE/scan.json" scripts/license-policy.jsonecho "=== License gate 3/3: UI npm production tree ==="-# The -ui binaries embed the compiled frontend bundle; its production-# dependency tree must be allow-listed too. --ignore-scripts: no dependency-# postinstall code runs inside the security job.+# The -ui archives ship the compiled frontend in an external asset pack; its+# production dependency tree must be allow-listed too. --ignore-scripts: no+# dependency postinstall code runs inside the security job.if command -v npm &>/dev/null && [ -f graph-ui/package-lock.json ]; thenif [ ! -d graph-ui/node_modules ]; then(cd graph-ui && npm ci --ignore-scripts --silent)diff --git a/scripts/license-policy.json b/scripts/license-policy.jsonindex 5ae9faa15..e65c532fc 100644--- a/scripts/license-policy.json+++ b/scripts/license-policy.json@@ -16,7 +16,7 @@"LicenseRef-scancode-public-domain","LicenseRef-scancode-public-domain-disclaimer"],- "_ignored_paths_comment": "Path prefixes (relative to the staged scan tree) excluded from the gate. Use ONLY for documented false positives. Justifications: the license tooling itself (gate scripts + this policy file) necessarily names prohibited licenses; gen-third-party-notices.sh echoes license terminology; audit-license-provenance.py names licenses in its verdict maps; src/discover/discover.c contains a license-FILENAME classification list (LICENSE-MIT, LICENSE-APACHE, ...) for file discovery, which ScanCode reads as license references; package-release.sh and smoke-local.sh list the archive members 'cbm-integrations.json LICENSE ...' adjacently (the order the Windows single-binary contract locks, mirrored by the smoke fixture), and ScanCode reads the '.json LICENSE' token adjacency as a reference to the SPDX 'JSON' license — first-party MIT build scripts, not vendored code.",+ "_ignored_paths_comment": "Path prefixes (relative to the staged scan tree) excluded from the gate. Use ONLY for documented false positives. Justifications: the license tooling itself (gate scripts + this policy file) necessarily names prohibited licenses; gen-third-party-notices.sh echoes license terminology; audit-license-provenance.py names licenses in its verdict maps; src/discover/discover.c contains a license-FILENAME classification list (LICENSE-MIT, LICENSE-APACHE, ...) for file discovery, which ScanCode reads as license references; package-release.sh and smoke-local.sh list the archive members 'cbm-integrations.json LICENSE ...' adjacently (the order the Windows one-executable runtime-set contract locks, mirrored by the smoke fixture), and ScanCode reads the '.json LICENSE' token adjacency as a reference to the SPDX 'JSON' license — first-party MIT build scripts, not vendored code.","ignored_paths": ["tree/scripts/license-policy.json","tree/scripts/license-gate-check.py",diff --git a/scripts/pack-ui-assets.mjs b/scripts/pack-ui-assets.mjsnew file mode 100644index 000000000..688728df8--- /dev/null+++ b/scripts/pack-ui-assets.mjs@@ -0,0 +1,211 @@+#!/usr/bin/env node+/*+ * Build a deterministic, uncompressed, content-addressed UI asset pack.+ *+ * The native binary receives only the pack name, exact byte length and+ * SHA-256. Frontend bytes stay outside ELF/Mach-O/PE and stay unobscured for+ * scanners, SBOM tools and human inspection.+ */+import crypto from 'node:crypto';+import fs from 'node:fs/promises';+import path from 'node:path';+import process from 'node:process';++const HEADER_BYTES = 80;+const ENTRY_BYTES = 24;+const FORMAT_VERSION = 1;+const MAX_FILES = 1024;+const MAX_PATH_BYTES = 255;+const MAX_PACK_BYTES = 64 * 1024 * 1024;++const MIME_BY_EXTENSION = new Map([+ ['.html', 1],+ ['.js', 2],+ ['.mjs', 2],+ ['.css', 3],+ ['.json', 4],+ ['.svg', 5],+ ['.png', 6],+ ['.jpg', 7],+ ['.jpeg', 7],+ ['.webp', 8],+ ['.avif', 9],+ ['.ico', 10],+ ['.woff2', 11],+ ['.woff', 12],+ ['.wasm', 13],+]);++function fail(message) {+ throw new Error(`pack-ui-assets: ${message}`);+}++function compareBytewise(left, right) {+ return Buffer.compare(Buffer.from(left, 'utf8'), Buffer.from(right, 'utf8'));+}++function validateUrlPath(urlPath) {+ const bytes = Buffer.from(urlPath, 'utf8');+ if (bytes.length < 2 || bytes.length > MAX_PATH_BYTES ||+ !/^[A-Za-z0-9._/-]+$/.test(urlPath) || urlPath.includes('//') ||+ urlPath.endsWith('/') || urlPath.includes('/./') || urlPath.includes('/../') ||+ urlPath.endsWith('/.') || urlPath.endsWith('/..')) {+ fail(`unsupported frontend path ${JSON.stringify(urlPath)}`);+ }+ if (urlPath !== '/index.html' && !urlPath.startsWith('/assets/')) {+ fail(`frontend output must contain only /index.html and /assets/* (got ${urlPath})`);+ }+ return bytes;+}++async function collectFiles(root, directory = root, relative = '') {+ const dirEntries = await fs.readdir(directory, { withFileTypes: true });+ dirEntries.sort((left, right) => compareBytewise(left.name, right.name));+ const files = [];+ for (const entry of dirEntries) {+ const absolute = path.join(directory, entry.name);+ const childRelative = relative ? path.posix.join(relative, entry.name) : entry.name;+ if (entry.isSymbolicLink()) {+ fail(`symbolic links are not allowed (${childRelative})`);+ }+ if (entry.isDirectory()) {+ files.push(...await collectFiles(root, absolute, childRelative));+ } else if (entry.isFile()) {+ const urlPath = `/${childRelative}`;+ const pathBytes = validateUrlPath(urlPath);+ const extension = path.posix.extname(childRelative).toLowerCase();+ const mimeId = MIME_BY_EXTENSION.get(extension);+ if (!mimeId) {+ fail(`no closed MIME mapping for ${urlPath}`);+ }+ const data = await fs.readFile(absolute);+ if (data.length === 0) {+ fail(`zero-length frontend assets are not supported (${urlPath})`);+ }+ files.push({+ urlPath,+ pathBytes,+ mimeId,+ cacheId: urlPath === '/index.html' ? 1 : 2,+ data,+ });+ } else {+ fail(`unsupported filesystem entry (${childRelative})`);+ }+ }+ return files;+}++function writeU64(buffer, value, offset) {+ if (!Number.isSafeInteger(value) || value < 0) fail('pack size exceeds safe integer range');+ buffer.writeBigUInt64LE(BigInt(value), offset);+}++function buildPack(files) {+ files.sort((left, right) => compareBytewise(left.urlPath, right.urlPath));+ if (files.length === 0 || files.length > MAX_FILES) {+ fail(`frontend file count must be between 1 and ${MAX_FILES}`);+ }+ if (files.filter((file) => file.urlPath === '/index.html').length !== 1) {+ fail('frontend output must contain exactly one /index.html');+ }+ for (let index = 1; index < files.length; index += 1) {+ if (compareBytewise(files[index - 1].urlPath, files[index].urlPath) >= 0) {+ fail(`duplicate or unsorted path ${files[index].urlPath}`);+ }+ }++ const indexBytes = files.length * ENTRY_BYTES;+ const pathsBytes = files.reduce((total, file) => total + file.pathBytes.length, 0);+ const payloadBytes = files.reduce((total, file) => total + file.data.length, 0);+ const indexOffset = HEADER_BYTES;+ const pathsOffset = indexOffset + indexBytes;+ const payloadOffset = pathsOffset + pathsBytes;+ const totalBytes = payloadOffset + payloadBytes;+ if (totalBytes > MAX_PACK_BYTES) {+ fail(`pack exceeds ${MAX_PACK_BYTES} bytes`);+ }++ const pack = Buffer.alloc(totalBytes);+ pack.write('CBMUIPK', 0, 7, 'ascii');+ pack[7] = 0;+ pack.writeUInt16LE(FORMAT_VERSION, 8);+ pack.writeUInt16LE(HEADER_BYTES, 10);+ pack.writeUInt32LE(0, 12);+ pack.writeUInt32LE(files.length, 16);+ pack.writeUInt32LE(ENTRY_BYTES, 20);+ writeU64(pack, indexOffset, 24);+ writeU64(pack, indexBytes, 32);+ writeU64(pack, pathsOffset, 40);+ writeU64(pack, pathsBytes, 48);+ writeU64(pack, payloadOffset, 56);+ writeU64(pack, payloadBytes, 64);+ writeU64(pack, totalBytes, 72);++ let pathCursor = 0;+ let payloadCursor = 0;+ files.forEach((file, index) => {+ const entryOffset = indexOffset + index * ENTRY_BYTES;+ pack.writeUInt32LE(pathCursor, entryOffset);+ pack.writeUInt16LE(file.pathBytes.length, entryOffset + 4);+ pack.writeUInt8(file.mimeId, entryOffset + 6);+ pack.writeUInt8(file.cacheId, entryOffset + 7);+ writeU64(pack, payloadCursor, entryOffset + 8);+ writeU64(pack, file.data.length, entryOffset + 16);+ file.pathBytes.copy(pack, pathsOffset + pathCursor);+ file.data.copy(pack, payloadOffset + payloadCursor);+ pathCursor += file.pathBytes.length;+ payloadCursor += file.data.length;+ });+ return pack;+}++async function writeAtomically(destination, bytes) {+ const temporary = `${destination}.tmp-${process.pid}`;+ try {+ await fs.writeFile(temporary, bytes, { flag: 'wx', mode: 0o644 });+ await fs.rename(temporary, destination);+ } catch (error) {+ await fs.rm(temporary, { force: true });+ throw error;+ }+}++async function main() {+ const [sourceRoot, outputDirectory, manifestPath, ...extra] = process.argv.slice(2);+ if (!sourceRoot || !outputDirectory || !manifestPath || extra.length !== 0) {+ fail('usage: pack-ui-assets.mjs <dist-dir> <output-dir> <manifest.c>');+ }+ const rootStat = await fs.lstat(sourceRoot);+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {+ fail('dist-dir must be a real directory, not a symlink');+ }+ const files = await collectFiles(sourceRoot);+ const pack = buildPack(files);+ const digest = crypto.createHash('sha256').update(pack).digest('hex');+ const packName = `cbm-ui-${digest}.pack`;+ const manifest = Buffer.from(+ '/* Generated by scripts/pack-ui-assets.mjs; do not edit. */\n' ++ '#include <stdint.h>\n\n' ++ `const char CBM_UI_ASSET_PACK_NAME[] = "${packName}";\n` ++ `const char CBM_UI_ASSET_SHA256[] = "${digest}";\n` ++ `const uint64_t CBM_UI_ASSET_SIZE = UINT64_C(${pack.length});\n`,+ 'utf8',+ );++ await fs.mkdir(outputDirectory, { recursive: true });+ await fs.mkdir(path.dirname(manifestPath), { recursive: true });+ const packPath = path.join(outputDirectory, packName);+ await writeAtomically(packPath, pack);+ await writeAtomically(manifestPath, manifest);++ const oldPacks = (await fs.readdir(outputDirectory))+ .filter((name) => /^cbm-ui-[0-9a-f]{64}\.pack$/.test(name) && name !== packName);+ await Promise.all(oldPacks.map((name) => fs.rm(path.join(outputDirectory, name))));+ process.stdout.write(`${packName} ${pack.length} bytes ${files.length} files\n`);+}++main().catch((error) => {+ process.stderr.write(`${error.message}\n`);+ process.exitCode = 1;+});diff --git a/scripts/package-release.sh b/scripts/package-release.shindex 2a837a918..97a47f545 100755--- a/scripts/package-release.sh+++ b/scripts/package-release.sh@@ -6,9 +6,8 @@# HERE, nowhere else, so a local artifact smoke provably exercises the same# bytes-layout the release publishes.#-# This script ARCHIVES what scripts/build.sh already produced — it never-# builds the product itself (the Windows launcher image is the one deliberate-# exception: it is part of the archive, not of the product build).+# This script ARCHIVES what scripts/build.sh already produced; it never builds+# or synthesizes another executable.set -euo pipefail@@ -28,6 +27,7 @@ local artifact-flow smoke lane.arm64-portable, ...)--variant standard (default) | ui — selects the archive NAME prefix; thematching binary must already have been built (--with-ui for ui).+ UI archives add exactly one root-level cbm-ui-<sha256>.pack.--out-dir where to place the archive (default: repository root).Make passthrough (VAR=VAL, forwarded to the build):@@ -36,11 +36,16 @@ Make passthrough (VAR=VAL, forwarded to the build):Environment:BUILD_DIR build tree to archive from (default build/c).-Archive contents (defined here, canonical) — ONE binary per platform:+Archive contents (defined here, canonical) — ONE executable per runtime set:unix: codebase-memory-mcp cbm-integrations.json LICENSE install.sh- THIRD_PARTY_NOTICES.md (.tar.gz)+ THIRD_PARTY_NOTICES.md [cbm-ui-<sha256>.pack] (.tar.gz)windows: codebase-memory-mcp.exe cbm-integrations.json LICENSE install.ps1- THIRD_PARTY_NOTICES.md (.zip)+ THIRD_PARTY_NOTICES.md [cbm-ui-<sha256>.pack] (.zip)++The bracketed pack is required only for the ui variant and forbidden from the+standard archive. The pack FORMAT is uncompressed before archiving; the tar/zip+container may compress it. Release extraction retains it as a standalone input+so scanners can inspect the frontend independently of the native image.cbm-integrations.json is the integration-template data file: the binaryembeds only its SHA-256 and refuses to install integrations without a@@ -98,6 +103,56 @@ BUILD_DIR="${BUILD_DIR:-build/c}"OUT_DIR="$(mkdir -p "$OUT_DIR" && cd "$OUT_DIR" && pwd)"NAME="codebase-memory-mcp${SUFFIX}-${GOOS}-${GOARCH}"+sha256_file() {+ local path="$1"+ if command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$path" | awk '{print $1}'+ elif command -v shasum >/dev/null 2>&1; then+ shasum -a 256 "$path" | awk '{print $1}'+ else+ echo "package-release: sha256sum or shasum is required to verify UI packs" >&2+ return 1+ fi+}++verify_ui_pack_digest() {+ local path="$1"+ local name expected actual+ name="$(basename "$path")"+ expected="${name#cbm-ui-}"+ expected="${expected%.pack}"+ if ! actual="$(sha256_file "$path")"; then+ return 1+ fi+ actual="$(printf '%s' "$actual" | tr 'A-F' 'a-f')"+ if ! [[ "$actual" =~ ^[0-9a-f]{64}$ ]] || [ "$actual" != "$expected" ]; then+ echo "package-release: UI pack digest does not match its filename: $name" >&2+ return 1+ fi+}++# Resolve the content-addressed UI sidecar before touching the binary. A loose+# glob is not the contract: every matching candidate must have the exact owned+# name shape, and a UI archive must contain exactly one of them.+UI_PACK_NAME=""+UI_PACK_SOURCE=""+if [ "$VARIANT" = "ui" ]; then+ shopt -s nullglob+ UI_PACK_CANDIDATES=("$BUILD_DIR"/cbm-ui-*.pack)+ shopt -u nullglob+ if [ "${#UI_PACK_CANDIDATES[@]}" -ne 1 ]; then+ echo "package-release: ui build must contain exactly one cbm-ui-<sha256>.pack" >&2+ exit 2+ fi+ UI_PACK_SOURCE="${UI_PACK_CANDIDATES[0]}"+ UI_PACK_NAME="$(basename "$UI_PACK_SOURCE")"+ if ! [[ "$UI_PACK_NAME" =~ ^cbm-ui-[0-9a-f]{64}\.pack$ ]] || [ ! -s "$UI_PACK_SOURCE" ]; then+ echo "package-release: invalid UI asset pack: $UI_PACK_SOURCE" >&2+ exit 2+ fi+ verify_ui_pack_digest "$UI_PACK_SOURCE" || exit 2+fi+# Ship every release binary stripped. Production already builds without -g, but# the linker still keeps a ~536 KB .symtab, so releases carried their full# symbol table to users: bigger downloads and a free map of the internals, with@@ -105,14 +160,12 @@ NAME="codebase-memory-mcp${SUFFIX}-${GOOS}-${GOARCH}"# production build and never calls backtrace_symbols), so this costs no# diagnostics.#-# It also had a concrete cost. Microsoft's ML scored the unstripped linux-amd64-# binary Trojan:Script/Wacatac.B!ml (1 engine of 62) and blocked release run-# 30398064336 at the VirusTotal gate. That verdict is a decision-boundary-# artifact rather than a property of the code -- the dry-run build two days-# earlier is the same program plus 10 KB and scans clean, and the ui build of-# the same commit was never flagged. Stripping removes the symbol surface those-# models score and cleared BOTH flagged builds (Wacatac.B and Wacatac.C)-# without changing what the program does.+# A historical unstripped linux-amd64 artifact was the sole Microsoft detection+# in release run 30398064336, while related stripped artifacts later scanned+# clean. That is useful release evidence but not controlled feature attribution:+# engine state and other bytes can differ between observations. Independently+# of the opaque verdict, stripping removes an unnecessary symbol surface and+# does not change program behavior.## macOS is ad-hoc signed by the build workflow BEFORE this script runs, and# stripping invalidates that signature, so Mach-O is re-signed here. Skipping@@ -160,45 +213,80 @@ strip_release_binary() {}if [ "$GOOS" = "windows" ]; then- # Windows ships ONE binary, exactly like every other platform. There is no+ # Windows ships one executable, exactly like every other runtime set. There is no# launcher stub: a small unsigned PE whose entire job is to verify and- # execute another binary is statically indistinguishable from a dropper,- # and Defender's ML scored it Trojan:Win32/Wacatac.B!ml on x64 regardless- # of what we changed (bcrypt-free, stripped, versioned, and even- # resource-free builds were all flagged, while the product binary itself- # scans clean on every platform). Self-update — the launcher's whole reason- # to exist — moves OUT of the running process into install.ps1: Windows'- # executable lock only blocks a process from replacing ITSELF.+ # execute another binary adds loader-like behavior and another artifact to+ # audit. Historical launcher builds received Microsoft Wacatac verdicts,+ # but that observation does not identify a stable feature or establish+ # causation. Self-update — the launcher's whole reason to exist — moves OUT+ # of the running process into install.ps1: Windows' executable lock only+ # blocks a process from replacing ITSELF.PAYLOAD="$BUILD_DIR/codebase-memory-mcp"[ -f "${PAYLOAD}.exe" ] && PAYLOAD="${PAYLOAD}.exe"[ -f "$PAYLOAD" ] || { echo "package-release: build first; missing $PAYLOAD" >&2; exit 2; }- PACK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/cbm-package.XXXXXX")"- trap 'rm -rf "$PACK_DIR"' EXIT- cp "$PAYLOAD" "$PACK_DIR/codebase-memory-mcp.exe"- strip_release_binary "$PACK_DIR/codebase-memory-mcp.exe" || exit 2- # Gate the artifact AFTER strip: strip is the last byte-changing step, so- # this inspects exactly what goes into the archive. Runs here rather than in- # a workflow step so the local artifact-flow smoke enforces the same thing.- bash scripts/ci/check-binary-composition.sh --variant="$VARIANT" \- "$PACK_DIR/codebase-memory-mcp.exe" || exit 2- cp LICENSE install.ps1 assets/cbm-integrations.json "$PACK_DIR/"- scripts/gen-third-party-notices.sh "$PACK_DIR/THIRD_PARTY_NOTICES.md"+ STAGED_BINARY_NAME="codebase-memory-mcp.exe"+ INSTALLER="install.ps1"+else+ PAYLOAD="$BUILD_DIR/codebase-memory-mcp"+ [ -f "$PAYLOAD" ] || { echo "package-release: build first; missing $PAYLOAD" >&2; exit 2; }+ STAGED_BINARY_NAME="codebase-memory-mcp"+ INSTALLER="install.sh"+fi++# Work from one owner-private directory for every target. The binary is copied+# here BEFORE strip/re-sign and the archive is created from this same directory,+# so the executable that validates the adjacent sidecars is byte-for-byte the+# executable users receive. Keeping the stage beside the build also avoids a+# system /tmp mounted noexec: the validation probe must actually execute.+PACK_DIR="$(mktemp -d "$BUILD_DIR/.cbm-package.XXXXXX")"+trap 'rm -rf "$PACK_DIR"' EXIT+STAGED_BINARY="$PACK_DIR/$STAGED_BINARY_NAME"+cp "$PAYLOAD" "$STAGED_BINARY"+strip_release_binary "$STAGED_BINARY" || exit 2++# Gate the artifact AFTER strip/re-sign: this is the final executable image and+# no later step may mutate it.+bash scripts/ci/check-binary-composition.sh --variant="$VARIANT" \+ "$STAGED_BINARY" || exit 2++# Stage the exact runtime association before any archive is created. Both+# sidecars are regular copies in an otherwise empty private directory. The UI+# pack's filename is self-authenticating, but only the executable knows whether+# that otherwise-valid pack (and integration manifest) belong to THIS build.+cp assets/cbm-integrations.json "$PACK_DIR/cbm-integrations.json"+if [ "$VARIANT" = "ui" ]; then+ cp "$UI_PACK_SOURCE" "$PACK_DIR/$UI_PACK_NAME"+fi+cp LICENSE "$INSTALLER" "$PACK_DIR/"+scripts/gen-third-party-notices.sh "$PACK_DIR/THIRD_PARTY_NOTICES.md"++if ! "$STAGED_BINARY" --verify-runtime-assets; then+ echo "package-release: staged binary rejected its adjacent runtime assets; refusing archive" >&2+ exit 2+fi+echo "=== package-release: staged runtime assets match $STAGED_BINARY_NAME ==="++if [ "$GOOS" = "windows" ]; then(cd "$PACK_DIR"rm -f "$OUT_DIR/$NAME.zip"- zip -q "$OUT_DIR/$NAME.zip" \- codebase-memory-mcp.exe cbm-integrations.json LICENSE install.ps1 THIRD_PARTY_NOTICES.md+ ARCHIVE_MEMBERS=(+ codebase-memory-mcp.exe cbm-integrations.json LICENSE install.ps1+ THIRD_PARTY_NOTICES.md+ )+ [ "$VARIANT" = "ui" ] && ARCHIVE_MEMBERS+=("$UI_PACK_NAME")+ zip -q "$OUT_DIR/$NAME.zip" "${ARCHIVE_MEMBERS[@]}")echo "=== package-release: $OUT_DIR/$NAME.zip ==="else- [ -f "$BUILD_DIR/codebase-memory-mcp" ] ||- { echo "package-release: build first; missing $BUILD_DIR/codebase-memory-mcp" >&2; exit 2; }- strip_release_binary "$BUILD_DIR/codebase-memory-mcp" || exit 2- bash scripts/ci/check-binary-composition.sh --variant="$VARIANT" \- "$BUILD_DIR/codebase-memory-mcp" || exit 2- cp LICENSE install.sh assets/cbm-integrations.json "$BUILD_DIR/"- scripts/gen-third-party-notices.sh "$BUILD_DIR/THIRD_PARTY_NOTICES.md"- tar -czf "$OUT_DIR/$NAME.tar.gz" -C "$BUILD_DIR" \- codebase-memory-mcp cbm-integrations.json LICENSE install.sh THIRD_PARTY_NOTICES.md+ ARCHIVE_MEMBERS=(+ codebase-memory-mcp cbm-integrations.json LICENSE install.sh+ THIRD_PARTY_NOTICES.md+ )+ [ "$VARIANT" = "ui" ] && ARCHIVE_MEMBERS+=("$UI_PACK_NAME")+ # BSD tar otherwise materializes macOS extended attributes as hidden+ # AppleDouble `._*` members, violating the exact five/six-file inventory.+ COPYFILE_DISABLE=1 tar -czf "$OUT_DIR/$NAME.tar.gz" -C "$PACK_DIR" \+ "${ARCHIVE_MEMBERS[@]}"echo "=== package-release: $OUT_DIR/$NAME.tar.gz ==="fidiff --git a/scripts/security-ui.sh b/scripts/security-ui.shindex 3827c06af..68c9720c0 100755--- a/scripts/security-ui.sh+++ b/scripts/security-ui.sh@@ -4,7 +4,7 @@ set -euo pipefail# Layer 6: Graph UI security audit.## Audits:-# A. Frontend asset scan (embedded JS/CSS/HTML or graph-ui/dist/)+# A. Frontend asset scan (source and external packed JS/CSS/HTML inputs)# B. HTTP server binding (must be 127.0.0.1 only)# C. RPC proxy scope (no system()/popen() in HTTP handler path)# D. CORS check (no wildcard Access-Control-Allow-Origin)@@ -25,7 +25,7 @@ echo "=== Layer 6: Graph UI Security Audit ==="echo ""echo "--- A. Frontend asset scan ---"-# Check both built dist and embedded asset source+# Check both source and the built files packed into the release sidecar.UI_DIRS=()[[ -d "$ROOT/graph-ui/dist" ]] && UI_DIRS+=("$ROOT/graph-ui/dist")[[ -d "$ROOT/graph-ui/src" ]] && UI_DIRS+=("$ROOT/graph-ui/src")diff --git a/scripts/security-vendored.sh b/scripts/security-vendored.shindex c6946917e..d12dd6e1e 100755--- a/scripts/security-vendored.sh+++ b/scripts/security-vendored.sh@@ -1,10 +1,11 @@#!/usr/bin/env bashset -euo pipefail-# Layer 8: Vendored dependency integrity — verifies vendored C sources match-# checked-in checksums. Detects supply chain tampering of vendored libraries.+# Layer 8: Vendored dependency integrity — verifies every vendored input matches+# checked-in checksums. Detects supply-chain tampering of source, generated+# parsers, assembly loaders, opaque data blobs, notices, and licenses.#-# Libraries covered: mimalloc, nomic, sqlite3, tre, xxhash, yyjson+# Scope: every regular file under vendored/ and internal/cbm/vendored/.## Usage: scripts/security-vendored.sh [--update]@@ -17,6 +18,8 @@ fiROOT="$(cd "$(dirname "$0")/.." && pwd -P)"CHECKSUMS="$ROOT/scripts/vendored-checksums.txt"VENDORED_ROOT="$ROOT/vendored"+INTERNAL_VENDORED_ROOT="$ROOT/internal/cbm/vendored"+VENDORED_ROOTS=("$VENDORED_ROOT")if [[ ! -f "$CHECKSUMS" || -L "$CHECKSUMS" ]]; thenecho "FAIL: checksum manifest must be a regular, non-symlink file: $CHECKSUMS"@@ -26,6 +29,13 @@ if [[ ! -d "$VENDORED_ROOT" || -L "$VENDORED_ROOT" ]]; thenecho "FAIL: vendored root must be a regular, non-symlink directory: $VENDORED_ROOT"exit 1fi+if [[ -e "$INTERNAL_VENDORED_ROOT" ]]; then+ if [[ ! -d "$INTERNAL_VENDORED_ROOT" || -L "$INTERNAL_VENDORED_ROOT" ]]; then+ echo "FAIL: internal vendored root must be a regular, non-symlink directory: $INTERNAL_VENDORED_ROOT"+ exit 1+ fi+ VENDORED_ROOTS+=("$INTERNAL_VENDORED_ROOT")+fiecho "=== Layer 8: Vendored Dependency Integrity ==="@@ -73,8 +83,7 @@ DISCOVERED=0valid_vendored_path() {local path="$1"- [[ "$path" == vendored/* ]] || return 1- [[ "$path" == *.c || "$path" == *.h ]] || return 1+ [[ "$path" == vendored/* || "$path" == internal/cbm/vendored/* ]] || return 1[[ "$path" != *'\\'* ]] || return 1[[ "$path" != *'//'* ]] || return 1[[ "$path" != *'/./'* && "$path" != */. ]] || return 1@@ -94,14 +103,17 @@ hash_file() {printf '%s\n' "$hash"}-# Inventory with NUL delimiters first. This makes path validation independent-# of whitespace and ensures find/read failures are structural, not silent skips.-if ! find "$VENDORED_ROOT" -type f \( -name '*.c' -o -name '*.h' \) -print0 \+# Inventory every regular vendored file with NUL delimiters first. Opaque data+# and assembly are as security-relevant as C headers: code_vectors.bin is+# linked verbatim through .incbin, while all generated grammar sources enter+# the product link. This makes path validation independent of whitespace and+# ensures find/read failures are structural, not silent skips.+if ! find "${VENDORED_ROOTS[@]}" -type f -print0 \> "$VENDORED_FILES"; then- echo "BLOCKED: cannot inventory vendored source files"+ echo "BLOCKED: cannot inventory vendored files"STRUCTURAL_FAIL=1fi-if ! find "$VENDORED_ROOT" -type l -print0 > "$VENDORED_SYMLINKS"; then+if ! find "${VENDORED_ROOTS[@]}" -type l -print0 > "$VENDORED_SYMLINKS"; thenecho "BLOCKED: cannot inspect vendored symlinks"STRUCTURAL_FAIL=1fi@@ -207,7 +219,7 @@ if [[ $CHECKED -eq 0 ]]; thenSTRUCTURAL_FAIL=1fiif [[ $DISCOVERED -eq 0 ]]; then- echo "BLOCKED: vendored inventory contains zero C/header files"+ echo "BLOCKED: vendored inventory contains zero files"STRUCTURAL_FAIL=1fidiff --git a/scripts/setup-windows.ps1 b/scripts/setup-windows.ps1index 592a9cd49..ac7731497 100644--- a/scripts/setup-windows.ps1+++ b/scripts/setup-windows.ps1@@ -213,7 +213,7 @@ if ($FromSource) {Write-Host ""Write-Host "Building binary (this may take a minute)..." -ForegroundColor White$wslBinaryPath = "/home/$wslUser/.local/bin/$BinaryName"- Invoke-WSL "mkdir -p /home/$wslUser/.local/bin && cd $sourceDir && scripts/build.sh && cp build/c/codebase-memory-mcp $wslBinaryPath"+ Invoke-WSL "mkdir -p /home/$wslUser/.local/bin && cd $sourceDir && scripts/build.sh && cp build/c/codebase-memory-mcp build/c/cbm-integrations.json /home/$wslUser/.local/bin/"Write-Ok "Built to $wslBinaryPath (inside WSL)"# Verify@@ -238,7 +238,7 @@ if ($FromSource) {Write-Ok "Done! Restart Claude Code and verify with /mcp"Write-Host ""Write-Host " To uninstall:" -ForegroundColor White- Write-Host " wsl.exe -- rm $wslBinaryPath"+ Write-Host " wsl.exe -- rm $wslBinaryPath /home/$wslUser/.local/bin/cbm-integrations.json"Write-Host " wsl.exe -- rm -rf $sourceDir"Write-Host " wsl.exe -- rm -rf ~/.cache/codebase-memory-mcp/"diff --git a/scripts/setup.sh b/scripts/setup.shindex 81a0508d3..fca5d7222 100755--- a/scripts/setup.sh+++ b/scripts/setup.sh@@ -144,6 +144,18 @@ fetch() {fi}+install_integration_asset() {+ local source_dir="$1"+ local source_path="${source_dir}/cbm-integrations.json"++ if [ ! -f "$source_path" ]; then+ die "Runtime asset missing from build or release: cbm-integrations.json"+ fi++ cp "$source_path" "${INSTALL_DIR}/cbm-integrations.json"+ chmod 644 "${INSTALL_DIR}/cbm-integrations.json"+}+download_binary() {local platform="$1" tool="$2"@@ -171,6 +183,7 @@ download_binary() {mkdir -p "$INSTALL_DIR"mv "${tmpdir}/${BINARY_NAME}" "${INSTALL_DIR}/${BINARY_NAME}"chmod +x "${INSTALL_DIR}/${BINARY_NAME}"+ install_integration_asset "$tmpdir"ok "Installed to ${INSTALL_DIR}/${BINARY_NAME}"}@@ -199,7 +212,10 @@ build_from_source() {echo "${BOLD}Building binary (this may take a minute)...${RESET}"mkdir -p "$INSTALL_DIR"- (cd "$SOURCE_DIR" && scripts/build.sh && cp build/c/codebase-memory-mcp "${INSTALL_DIR}/${BINARY_NAME}")+ (cd "$SOURCE_DIR" && scripts/build.sh)+ cp "${SOURCE_DIR}/build/c/codebase-memory-mcp" "${INSTALL_DIR}/${BINARY_NAME}"+ chmod +x "${INSTALL_DIR}/${BINARY_NAME}"+ install_integration_asset "${SOURCE_DIR}/build/c"ok "Built and installed to ${INSTALL_DIR}/${BINARY_NAME}"}@@ -331,5 +347,6 @@ ok "Done! Restart Claude Code and verify with /mcp"echo ""info "To uninstall:"info " rm ${INSTALL_DIR}/${BINARY_NAME}"+info " rm ${INSTALL_DIR}/cbm-integrations.json"info " rm -rf ${SOURCE_DIR} # if built from source"info " rm -rf ~/.cache/codebase-memory-mcp/ # graph database"diff --git a/scripts/smoke-local.sh b/scripts/smoke-local.shindex b97292560..74cf03d02 100755--- a/scripts/smoke-local.sh+++ b/scripts/smoke-local.sh@@ -21,14 +21,15 @@ destination override neutralized.Arguments:<binary> Product binary to smoke (e.g. build/c/codebase-memory-mcp).- ui Mirror the -ui asset naming AND require the embedded UI:+ ui Mirror the -ui asset naming AND require the external UI pack:Phase 15's "no assets" outcome becomes a FAILURE(SMOKE_REQUIRE_UI=1), so a standard binary cannot pass a ui run.Environment:CBM_SMOKE_ARTIFACT_DIR Release mode: an EXTRACTED release artifact- directory. Sidecars (LICENSE, install.sh, THIRD_PARTY_NOTICES.md)- are validated and served from THERE instead of regenerated, so+ directory. Sidecars (LICENSE, install.sh, THIRD_PARTY_NOTICES.md,+ and the UI pack when selected) are validated and served from+ THERE instead of regenerated, sothe release venue smokes exactly the bytes it publishes; anincomplete archive fails the smoke. Unset (default): sidecarscome from this checkout (local/PR mode).@@ -56,9 +57,9 @@ if [ ! -x "$BINARY" ]; thenecho "smoke-local: binary is not executable: $BINARY" >&2exit 2fi-# 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+# A ui run must be handed a binary with exactly one external asset pack beside+# it; the suffix alone only renames the archive. SMOKE_REQUIRE_UI turns Phase+# 15's documented "no UI assets" SKIP into a failure, so asking for ui and# supplying a standard binary can no longer pass quietly.case "$VARIANT" instandard) SUFFIX="" ; REQUIRE_UI=0 ;;@@ -80,6 +81,37 @@ if [ -n "$ARTIFACT_DIR" ]; thendonefi+UI_PACK_NAME=""+UI_PACK_SOURCE=""+UI_PACK_COUNT=0+if [ -n "$ARTIFACT_DIR" ]; then+ UI_PACK_SOURCE_DIR="$ARTIFACT_DIR"+else+ UI_PACK_SOURCE_DIR="$(dirname "$BINARY")"+fi+shopt -s nullglob+UI_PACK_CANDIDATES=("$UI_PACK_SOURCE_DIR"/cbm-ui-*.pack)+shopt -u nullglob+for candidate in "${UI_PACK_CANDIDATES[@]+"${UI_PACK_CANDIDATES[@]}"}"; do+ UI_PACK_COUNT=$((UI_PACK_COUNT + 1))+ UI_PACK_SOURCE="$candidate"+ candidate_name="$(basename "$candidate")"+ if ! [[ "$candidate_name" =~ ^cbm-ui-[0-9a-f]{64}\.pack$ ]]; then+ echo "smoke-local: invalid UI pack name beside artifact: $candidate_name" >&2+ exit 2+ fi+done+if [ "$VARIANT" = "ui" ]; then+ if [ "$UI_PACK_COUNT" -ne 1 ] || [ ! -s "$UI_PACK_SOURCE" ]; then+ echo "smoke-local: ui fixture requires exactly one content-addressed UI pack" >&2+ exit 2+ fi+ UI_PACK_NAME="$(basename "$UI_PACK_SOURCE")"+elif [ "$UI_PACK_COUNT" -ne 0 ]; then+ echo "smoke-local: standard fixture must not contain a UI asset pack" >&2+ exit 2+fi+case "$(uname -s)" inDarwin) OS=darwin ;;Linux) OS=linux ;;@@ -129,28 +161,28 @@ elsecp "$ROOT/assets/cbm-integrations.json" "$ROOT/LICENSE" "$ROOT/install.sh" "$FIXTURE_DIR/""$ROOT/scripts/gen-third-party-notices.sh" "$FIXTURE_DIR/THIRD_PARTY_NOTICES.md"fi+if [ -n "$UI_PACK_SOURCE" ]; then+ cp "$UI_PACK_SOURCE" "$FIXTURE_DIR/$UI_PACK_NAME"+fi# The archive must carry cbm-integrations.json — install verifies it against the# binary's embedded SHA-256 and fails closed without it. Member set and ORDER-# mirror scripts/package-release.sh (the Windows single-binary contract locks-# that order); a fixture that omits it would smoke a release layout we never ship.+# mirror scripts/package-release.sh (the Windows one-executable runtime-set+# contract locks that order); a fixture that omits it would smoke a release+# layout we never ship.EXPECTED_ARTIFACT="codebase-memory-mcp${SUFFIX}-${OS}-${ARCH}.tar.gz"-tar -czf "$FIXTURE_DIR/$EXPECTED_ARTIFACT" -C "$FIXTURE_DIR" \- codebase-memory-mcp cbm-integrations.json LICENSE install.sh THIRD_PARTY_NOTICES.md-if [ -n "$SUFFIX" ]; then- cp "$FIXTURE_DIR/$EXPECTED_ARTIFACT" \- "$FIXTURE_DIR/codebase-memory-mcp-${OS}-${ARCH}.tar.gz"-fi+ARCHIVE_MEMBERS=(+ codebase-memory-mcp cbm-integrations.json LICENSE install.sh+ THIRD_PARTY_NOTICES.md+)+[ -n "$UI_PACK_NAME" ] && ARCHIVE_MEMBERS+=("$UI_PACK_NAME")+tar -czf "$FIXTURE_DIR/$EXPECTED_ARTIFACT" -C "$FIXTURE_DIR" "${ARCHIVE_MEMBERS[@]}"# Linux install/update resolves the portable release asset even when this local# smoke started from the dynamic production binary.if [ "$OS" = "linux" ]; thencp "$FIXTURE_DIR/$EXPECTED_ARTIFACT" \"$FIXTURE_DIR/codebase-memory-mcp${SUFFIX}-${OS}-${ARCH}-portable.tar.gz"- if [ -n "$SUFFIX" ]; then- cp "$FIXTURE_DIR/codebase-memory-mcp${SUFFIX}-${OS}-${ARCH}-portable.tar.gz" \- "$FIXTURE_DIR/codebase-memory-mcp-${OS}-${ARCH}-portable.tar.gz"- fifi(cd "$FIXTURE_DIR" && { sha256sum *.tar.gz > checksums.txt 2>/dev/null ||shasum -a 256 *.tar.gz > checksums.txt; })diff --git a/scripts/smoke-test.sh b/scripts/smoke-test.shindex f0c680f94..1688a0edc 100755--- a/scripts/smoke-test.sh+++ b/scripts/smoke-test.sh@@ -40,6 +40,32 @@ if [ -n "$SMOKE_MODE" ] && [ "$SMOKE_MODE" != "--agent-config-only" ]; thenexit 2fiREPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")/.." && pwd)"+SMOKE_REQUIRE_UI="${SMOKE_REQUIRE_UI:-0}"++# A UI binary is a two-file runtime contract: native image plus exactly one+# content-addressed pack beside it. Remember that source pack so every fixture+# copy below stages the same sidecar rather than silently testing a binary-only+# layout that no UI release ships.+SMOKE_UI_PACK=""+SMOKE_UI_PACK_COUNT=0+shopt -s nullglob+SMOKE_UI_PACK_CANDIDATES=("$(dirname "$BINARY")"/cbm-ui-*.pack)+shopt -u nullglob+for candidate in "${SMOKE_UI_PACK_CANDIDATES[@]+"${SMOKE_UI_PACK_CANDIDATES[@]}"}"; do+ SMOKE_UI_PACK_COUNT=$((SMOKE_UI_PACK_COUNT + 1))+ SMOKE_UI_PACK="$candidate"+ candidate_name="$(basename "$candidate")"+ if ! [[ "$candidate_name" =~ ^cbm-ui-[0-9a-f]{64}\.pack$ ]]; then+ echo "FAIL: invalid UI asset pack name beside smoke binary: $candidate_name"+ exit 1+ fi+done+if [ "$SMOKE_REQUIRE_UI" = "1" ]; then+ if [ "$SMOKE_UI_PACK_COUNT" -ne 1 ] || [ ! -s "$SMOKE_UI_PACK" ]; then+ echo "FAIL: SMOKE_REQUIRE_UI=1 requires exactly one UI asset pack beside $BINARY"+ exit 1+ fi+fismoke_mktemp_file() {if [ -n "${SMOKE_TEMP_ROOT:-}" ]; then@@ -93,11 +119,14 @@ smoke_rmtree() {return 0}-# Every platform ships ONE binary, Windows included: a fixture copy is complete-# with nothing beside it.+# Every platform ships one native binary. UI runtime copies also require their+# external, content-addressed pack beside that binary.copy_smoke_binary() {local destination="$1"cp "$BINARY" "$destination"+ if [ -n "$SMOKE_UI_PACK" ]; then+ cp "$SMOKE_UI_PACK" "$(dirname "$destination")/$(basename "$SMOKE_UI_PACK")"+ fi}# Retire the shared account daemon (if one is running) and wait until it@@ -1061,7 +1090,7 @@ echo "OK: uninstall --dry-run completed"# handoff: it prints the shipped install script's command and exits 0. An# in-process updater is structurally a downloader -- fetch archive, extract,# chmod, exec -- which is impossible on Windows without a second resident-# binary, and is the shape Defender's ML scores as a dropper everywhere else.+# binary, and is unnecessary dropper-like surface in every platform artifact.echo "--- Phase 6c: update --dry-run ---"if [[ "$BINARY" == *.exe ]]; thenUPDATE_SCRIPT="install.ps1"@@ -1340,7 +1369,7 @@ if [[ "$BINARY" == *.exe ]]; thenecho "FAIL 8-0: installed binary missing after install"exit 1fi- # ONE binary, one link: a second hard link here would mean the retired+ # ONE executable, one link: a second hard link here would mean the retired# launcher/generation layout came back.PHASE8_LINKS=$(stat -c %h "$PHASE8_CANONICAL" 2>/dev/null || echo 1)if [ "$PHASE8_LINKS" != "1" ]; then@@ -2453,11 +2482,11 @@ echo "OK 8aw: all supported Scout/Verify/Auditor profile sets"echo ""echo "=== Phase 9: agent config uninstall E2E ==="-# Run uninstall (same FAKE_HOME with all configs present)-UNINSTALL_BINARY="$BINARY"-if [[ "$BINARY" == *.exe ]]; then- UNINSTALL_BINARY="$SELF_PATH"-fi+# Run uninstall from the installed copy. Uninstall intentionally targets the+# exact executable that invoked it; using the build input here removes the+# harness binary on POSIX and makes every later adversarial case test a missing+# command instead of the product.+UNINSTALL_BINARY="$SELF_PATH"HOME="$FAKE_HOME" \XDG_CONFIG_HOME="$FAKE_HOME/.config" \APPDATA="$FAKE_HOME/AppData/Roaming" \@@ -2856,8 +2885,14 @@ smoke_rmtree "$IDEM_HOME"# 9b-3: Uninstall without prior installCLEAN_HOME=$(smoke_mktemp_dir)mkdir -p "$CLEAN_HOME/.claude" "$CLEAN_HOME/.local/bin"+CLEAN_UNINSTALLER="$CLEAN_HOME/cbm-uninstall-driver"+if [[ "$BINARY" == *.exe ]]; then+ CLEAN_UNINSTALLER="$CLEAN_UNINSTALLER.exe"+fi+copy_smoke_binary "$CLEAN_UNINSTALLER"+chmod 755 "$CLEAN_UNINSTALLER"UNINSTALL_RC=0-UNINSTALL_OUT=$(HOME="$CLEAN_HOME" "$BINARY" uninstall -y -n 2>&1) || UNINSTALL_RC=$?+UNINSTALL_OUT=$(HOME="$CLEAN_HOME" "$CLEAN_UNINSTALLER" uninstall -y -n 2>&1) || UNINSTALL_RC=$?if [ "$UNINSTALL_RC" -ge 128 ]; thenecho "FAIL 9b-3: uninstall crashed (rc=$UNINSTALL_RC)"exit 1@@ -2880,14 +2915,18 @@ smoke_rmtree "$CORRUPT_HOME"# 9b-8: Double uninstallDBL_HOME=$(smoke_mktemp_dir)mkdir -p "$DBL_HOME/.claude" "$DBL_HOME/.local/bin"-copy_smoke_binary "$DBL_HOME/.local/bin/codebase-memory-mcp"-run_no_crash 9b-8-install env HOME="$DBL_HOME" "$BINARY" install -y-DBL_UNINSTALLER="$BINARY"+DBL_UNINSTALLER="$DBL_HOME/.local/bin/codebase-memory-mcp"+DBL_RETRY_UNINSTALLER="$DBL_HOME/cbm-uninstall-retry"if [[ "$BINARY" == *.exe ]]; then- DBL_UNINSTALLER="$DBL_HOME/.local/bin/codebase-memory-mcp.exe"+ DBL_UNINSTALLER="$DBL_UNINSTALLER.exe"+ DBL_RETRY_UNINSTALLER="$DBL_RETRY_UNINSTALLER.exe"fi+copy_smoke_binary "$DBL_UNINSTALLER"+copy_smoke_binary "$DBL_RETRY_UNINSTALLER"+chmod 755 "$DBL_UNINSTALLER" "$DBL_RETRY_UNINSTALLER"+run_no_crash 9b-8-install env HOME="$DBL_HOME" "$BINARY" install -yrun_no_crash 9b-8-first env HOME="$DBL_HOME" "$DBL_UNINSTALLER" uninstall -y -n-run_no_crash 9b-8-second env HOME="$DBL_HOME" "$BINARY" uninstall -y -n+run_no_crash 9b-8-second env HOME="$DBL_HOME" "$DBL_RETRY_UNINSTALLER" uninstall -y -necho "OK 9b-8: double uninstall doesn't crash"retire_account_daemon "9b-8-cleanup"smoke_rmtree "$DBL_HOME"@@ -3075,15 +3114,15 @@ if [ -n "${SMOKE_DOWNLOAD_URL:-}" ]; then# otherwise the uninstall this phase drives fails closed rendering templates.BINARY_ASSET="$(dirname "$BINARY")/cbm-integrations.json"if [[ "$BINARY" == *.exe ]]; then- cp "$BINARY" "$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe"+ copy_smoke_binary "$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe"mkdir -p "$UPDATE_HOME/retired-install"- cp "$BINARY" "$UPDATE_HOME/retired-install/codebase-memory-mcp.exe"+ copy_smoke_binary "$UPDATE_HOME/retired-install/codebase-memory-mcp.exe"[ -f "$BINARY_ASSET" ] && cp "$BINARY_ASSET" "$UPDATE_HOME/.local/bin/cbm-integrations.json"else- cp "$BINARY" "$UPDATE_HOME/.local/bin/codebase-memory-mcp"+ copy_smoke_binary "$UPDATE_HOME/.local/bin/codebase-memory-mcp"chmod 755 "$UPDATE_HOME/.local/bin/codebase-memory-mcp"mkdir -p "$UPDATE_HOME/retired-install"- cp "$BINARY" "$UPDATE_HOME/retired-install/codebase-memory-mcp"+ copy_smoke_binary "$UPDATE_HOME/retired-install/codebase-memory-mcp"chmod 755 "$UPDATE_HOME/retired-install/codebase-memory-mcp"[ -f "$BINARY_ASSET" ] && cp "$BINARY_ASSET" "$UPDATE_HOME/.local/bin/cbm-integrations.json"if [ "$(uname -s)" = "Darwin" ]; then@@ -3139,9 +3178,10 @@ if [ -n "${SMOKE_DOWNLOAD_URL:-}" ]; then# Contract, every platform: update NEVER replaces the running image in# process. It exits 0 and prints the shipped install script's command. On- # Windows regressing this means reintroducing the AV-flagged launcher stub;+ # Windows regressing this means reintroducing the removed launcher stub;# everywhere else it means putting download -> extract -> chmod -> exec back- # into the product binary.+ # into the product binary. Historical scanner results motivated measuring+ # this boundary but do not attribute a classifier decision to it.if [ "$UPDATE_RC" -ne 0 ]; thenecho "FAIL 14a: update exited rc=$UPDATE_RC (expected 0)"exit 1@@ -3281,6 +3321,7 @@ fi# Try standard name first, fall back to UI variantDL_ARCHIVE="codebase-memory-mcp-${DL_OS}-${DL_ARCH}.${DL_EXT}"DL_ARCHIVE_UI="codebase-memory-mcp-ui-${DL_OS}-${DL_ARCH}.${DL_EXT}"+DL_VARIANT_ARG="--standard"# 12a: curl download (try standard, then UI variant)echo "--- Phase 12a: curl download ---"@@ -3293,6 +3334,7 @@ if ! curl -fSL --noproxy '*' -o "$DL_DIR/$DL_ARCHIVE" "$SMOKE_DOWNLOAD_URL/$DL_A# Try UI variantif curl -fSL --noproxy '*' -o "$DL_DIR/$DL_ARCHIVE_UI" "$SMOKE_DOWNLOAD_URL/$DL_ARCHIVE_UI" 2>>"$CURL12_ERR"; thenDL_ARCHIVE="$DL_ARCHIVE_UI"+ DL_VARIANT_ARG="--ui"elseecho "FAIL 12a: curl download failed (tried standard and ui variants)"echo "--- curl stderr (url: $SMOKE_DOWNLOAD_URL/$DL_ARCHIVE) ---"@@ -3339,8 +3381,8 @@ echo "--- Phase 12d: extraction ---"(cd "$DL_DIR" && if [ "$DL_EXT" = "zip" ]; then unzip -q "$DL_ARCHIVE"; else tar -xzf "$DL_ARCHIVE"; fi)if [ "$DL_OS" = "windows" ]; thenDL_BIN="$DL_DIR/codebase-memory-mcp.exe"- # ONE binary per platform: a second executable in the archive would mean the- # AV-flagged launcher/payload split came back.+ # ONE executable per runtime set: a second executable in the archive would+ # mean the removed launcher/payload split came back.if [ -e "$DL_DIR/codebase-memory-mcp.payload.exe" ]; thenecho "FAIL 12d: Windows archive still ships a launcher/payload pair"exit 1@@ -3348,6 +3390,20 @@ if [ "$DL_OS" = "windows" ]; thenelseDL_BIN="$DL_DIR/codebase-memory-mcp"fi++shopt -s nullglob+DL_UI_PACKS=("$DL_DIR"/cbm-ui-*.pack)+shopt -u nullglob+if [ "$DL_VARIANT_ARG" = "--ui" ]; then+ if [ "${#DL_UI_PACKS[@]}" -ne 1 ] ||+ ! [[ "$(basename "${DL_UI_PACKS[0]}")" =~ ^cbm-ui-[0-9a-f]{64}\.pack$ ]]; then+ echo "FAIL 12d: UI archive does not contain exactly one content-addressed pack"+ exit 1+ fi+elif [ "${#DL_UI_PACKS[@]}" -ne 0 ]; then+ echo "FAIL 12d: standard archive contains a UI asset pack"+ exit 1+fiif [ ! -f "$DL_BIN" ]; thenecho "FAIL 12d: binary not found after extraction"exit 1@@ -3397,7 +3453,7 @@ if [ "$DL_OS" != "windows" ] && [ -f "$REPO_ROOT/install.sh" ]; then# 13a: run install.sh with local URL + isolated HOMEHOME="$INSTALL_TEST_HOME" CBM_DOWNLOAD_URL="$SMOKE_DOWNLOAD_URL" \- "$REPO_ROOT/install.sh" --dir="$INSTALL_TEST_DIR" 2>&1 || true+ "$REPO_ROOT/install.sh" "$DL_VARIANT_ARG" --dir="$INSTALL_TEST_DIR" 2>&1 || true# 13b: binary placedif [ ! -f "$INSTALL_TEST_DIR/codebase-memory-mcp" ]; then@@ -3406,6 +3462,21 @@ if [ "$DL_OS" != "windows" ] && [ -f "$REPO_ROOT/install.sh" ]; thenfiecho "OK 13b: binary placed"+ shopt -s nullglob+ INSTALLED_UI_PACKS=("$INSTALL_TEST_DIR"/cbm-ui-*.pack)+ shopt -u nullglob+ if [ "$DL_VARIANT_ARG" = "--ui" ]; then+ if [ "${#INSTALLED_UI_PACKS[@]}" -ne 1 ] ||+ ! [[ "$(basename "${INSTALLED_UI_PACKS[0]}")" =~ ^cbm-ui-[0-9a-f]{64}\.pack$ ]]; then+ echo "FAIL 13b: install.sh did not publish exactly one UI asset pack"+ exit 1+ fi+ echo "OK 13b: UI asset pack placed before binary activation"+ elif [ "${#INSTALLED_UI_PACKS[@]}" -ne 0 ]; then+ echo "FAIL 13b: standard install retained a UI asset pack"+ exit 1+ fi+# 13c: binary runs# Sign if needed on macOSif [ "$DL_OS" = "darwin" ]; then@@ -3480,7 +3551,7 @@ elif [ -f "$REPO_ROOT/install.ps1" ] && command -v powershell.exe &>/dev/null; tif ! HOME="$WIN_HOME" TEMP="$WIN_HOME" TMP="$WIN_HOME" \CBM_DOWNLOAD_URL="$WIN_URL" CBM_ARCH="$DL_ARCH" MSYS2_ARG_CONV_EXCL='*' \powershell.exe -NoProfile -ExecutionPolicy Bypass -File \- "$WIN_SCRIPT" "--dir=$WIN_DIR" 2>&1; then+ "$WIN_SCRIPT" "$DL_VARIANT_ARG" "--dir=$WIN_DIR" 2>&1; thenecho "FAIL 13f: install.ps1 execution failed"exit 1fi@@ -3497,6 +3568,21 @@ elif [ -f "$REPO_ROOT/install.ps1" ] && command -v powershell.exe &>/dev/null; texit 1fi+ shopt -s nullglob+ PS1_UI_PACKS=("$PS1_TEST_DIR"/cbm-ui-*.pack)+ shopt -u nullglob+ if [ "$DL_VARIANT_ARG" = "--ui" ]; then+ if [ "${#PS1_UI_PACKS[@]}" -ne 1 ] ||+ ! [[ "$(basename "${PS1_UI_PACKS[0]}")" =~ ^cbm-ui-[0-9a-f]{64}\.pack$ ]]; then+ echo "FAIL 13g: install.ps1 did not publish exactly one UI asset pack"+ exit 1+ fi+ echo "OK 13g: UI asset pack placed before binary activation"+ elif [ "${#PS1_UI_PACKS[@]}" -ne 0 ]; then+ echo "FAIL 13g: standard install retained a UI asset pack"+ exit 1+ fi+# 13h: binary runsif "$PS1_BIN" --version > /dev/null 2>&1; thenecho "OK 13h: binary runs"@@ -3516,22 +3602,38 @@ elsefi# ── Phase 15: UI HTTP server reachability ──-# Only runs if the binary was built with embedded UI assets.+# Only runs if the binary has a verified external UI asset pack.## SMOKE_REQUIRE_UI=1 (set by the wrappers for a -ui variant) makes the# no-assets outcome a FAILURE instead of a SKIP: a ui run that smoked a# standard binary under a ui name would otherwise pass green, and a skip that# cannot fail is not a gate.-SMOKE_REQUIRE_UI="${SMOKE_REQUIRE_UI:-0}"smoke_ui_missing() {if [ "$SMOKE_REQUIRE_UI" = "1" ]; then- echo "FAIL $1: SMOKE_REQUIRE_UI=1 but this binary serves no embedded UI assets"- kill "$UI_PID" 2>/dev/null || true+ echo "FAIL $1: SMOKE_REQUIRE_UI=1 but this binary serves no external UI assets"+ stop_ui_probeexit 1fiecho "SKIP $1: $2"}+# Keep stdin open without putting the product in a background pipeline. Bash+# waits for every member of such a pipeline, so a headless binary that exits+# immediately used to strand the `sleep 300` producer and pause the smoke for+# five minutes. A process-substitution producer has its own PID and can always+# be reaped explicitly on success, skip, or failure.+stop_ui_probe() {+ if [ -n "${UI_PID:-}" ]; then+ kill "$UI_PID" 2>/dev/null || true+ wait "$UI_PID" 2>/dev/null || true+ fi+ if [ -n "${UI_STDIN_PID:-}" ]; then+ kill "$UI_STDIN_PID" 2>/dev/null || true+ wait "$UI_STDIN_PID" 2>/dev/null || true+ fi+ exec 9<&- 2>/dev/null || true+}+echo ""echo "=== Phase 15: UI HTTP server ==="@@ -3542,15 +3644,17 @@ UI_PORT=$(python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0# --ui=true is REQUIRED: the HTTP UI is a persisted, default-off setting, so# on any fresh profile (every CI runner, every smoke HOME) a bare --port# invocation can never serve — the probe then misread "UI disabled" as "no-# embedded assets" on binaries that carry them (first exposed when the+# assets" on binaries with a valid pack (first exposed when the# ui-variant no-skip guard made Phase 15 mandatory). Stdin must be HELD OPEN:# the UI does not pin the process, so stdio EOF ends it cleanly (rc=0) before# the poll can see it serve — the drive-listing guard holds a pipe for the# same reason. Equals-form flags match that guard's proven invocation.-sleep 300 | "$BINARY" --ui=true --port="$UI_PORT" > /dev/null 2>&1 &+exec 9< <(sleep 300)+UI_STDIN_PID=$!+"$BINARY" --ui=true --port="$UI_PORT" <&9 > /dev/null 2>&1 &UI_PID=$!# Readiness poll instead of a fixed sleep: SKIP is legitimate ONLY when the-# process exited (the documented no-embedded-assets case); a slow start on a+# process exited (the documented no-asset-pack case); a slow start on a# loaded runner must not masquerade as it. The UI binds ~6s after launch even# on a fast host (measured against the release artifact), so the window# matches the drive-listing guard's 25s, not a 10s sprint.@@ -3562,15 +3666,15 @@ for _ in $(seq 1 150); dodoneif [ "$UI_READY" -eq 1 ] || kill -0 "$UI_PID" 2>/dev/null; then- # 15a: GET / returns 200 with HTML content+ # 15a: GET / returns 200 with HTML content from the external packUI_BODY=$(curl -sf "http://127.0.0.1:$UI_PORT/" 2>/dev/null || echo "")if echo "$UI_BODY" | grep -qi "<html"; thenecho "OK 15a: UI serves HTML at /"elif [ -z "$UI_BODY" ]; then- smoke_ui_missing "15a" "UI not reachable (binary may not have embedded assets)"+ smoke_ui_missing "15a" "UI not reachable (binary may not have a valid asset pack)"elseecho "FAIL 15a: UI root did not return HTML"- kill "$UI_PID" 2>/dev/null || true+ stop_ui_probeexit 1fi@@ -3586,15 +3690,13 @@ if [ "$UI_READY" -eq 1 ] || kill -0 "$UI_PID" 2>/dev/null; thensmoke_ui_missing "15b" "/api/ui-config not reachable"elseecho "FAIL 15b: /api/ui-config did not return JSON"- kill "$UI_PID" 2>/dev/null || true+ stop_ui_probeexit 1fi-- kill "$UI_PID" 2>/dev/null || true- wait "$UI_PID" 2>/dev/null || trueelse- smoke_ui_missing "Phase 15" "binary exited immediately (no UI assets embedded)"+ smoke_ui_missing "Phase 15" "binary exited immediately (no UI asset pack loaded)"fi+stop_ui_probeecho ""echo "=== Phase 16: stdio server leaves no orphan after shutdown ==="diff --git a/scripts/test-windows.ps1 b/scripts/test-windows.ps1index 8c1a8358a..2709e3d03 100644--- a/scripts/test-windows.ps1+++ b/scripts/test-windows.ps1@@ -6,7 +6,8 @@Builds the product binary if it is not already present, stages it under itsrelease name, then runs the deterministic Windows integration tests undertests/windows/ against it (real stdio / CLI / HTTP UI, real SQLite DB).- Windows ships ONE binary, exactly like Linux and macOS.+ Windows ships one native executable inside the same verified runtime-set+ layout as Linux and macOS.Two categories of test:@@ -21,8 +22,11 @@* test_daemon_stability.py guards the daemon parametersurface, crash recovery, busy-stop refusal, and churn* test_windows_update_handoff.py guards that `update`- hands off to install.ps1 instead of replacing its own- running image (the removed launcher stub's only job)+ hands off to install.ps1 instead of replacing its+ currently running executable+ * test_daemon_open_readiness.py guards that+ `daemon start --open` waits for the verified CBM UI+ endpoint while ordinary daemon startup remains asynchronousKNOWN REDS - genuine, still-open Windows bugs reproduced at the productsurface. They are EXPECTED to be RED (exit 1) and are opt-in@@ -46,7 +50,7 @@.PARAMETER TargetMakefile.cbm target used when building: 'cbm-with-ui' (default; needed for the- drive-picker guard's embedded HTTP UI) or 'cbm' (no UI - the drive guard then+ drive-picker guard's UI-enabled HTTP service) or 'cbm' (no UI - the drive guard thenreports a precondition and is skipped)..PARAMETER GuardsOnly@@ -89,9 +93,13 @@ function Resolve-Binary {param([string]$Explicit)if ($Explicit) { return (Resolve-Path $Explicit).Path }$built = Join-Path $repoRoot "build\c\codebase-memory-mcp.exe"- if (Test-Path $built) { return $built }Write-Host "Building $Target via Makefile.cbm ..." -ForegroundColor Cyan- & $Make "-j" "-f" "Makefile.cbm" $Target "SANITIZE=" "TMP=$tmp" "TEMP=$tmp" "TMPDIR=$tmp" | Out-Host+ $makeArgs = @(+ "-j", "-f", "Makefile.cbm", $Target, "SANITIZE=",+ "TMP=$tmp", "TEMP=$tmp", "TMPDIR=$tmp"+ )+ if ($Target -eq "cbm-with-ui") { $makeArgs += "TEST_SEAMS=1" }+ & $Make @makeArgs | Out-Host$buildExit = $LASTEXITCODEif ($buildExit -ne 0) { throw "build failed (exit $buildExit)" }if (-not (Test-Path $built)) { throw "binary not produced at $built" }@@ -134,12 +142,22 @@ try {New-Item -ItemType Directory -Path $guardBundle | Out-Null$guardBin = Join-Path $guardBundle "codebase-memory-mcp.exe"Copy-Item -LiteralPath $bin -Destination $guardBin+ $sourceRuntimeDir = Split-Path -Parent $bin+ $sourceIntegration = Join-Path $sourceRuntimeDir "cbm-integrations.json"+ if (-not (Test-Path -LiteralPath $sourceIntegration -PathType Leaf)) {+ throw "Windows guard source runtime is missing cbm-integrations.json beside $bin"+ }+ Copy-Item -LiteralPath $sourceIntegration -Destination $guardBundle+ Get-ChildItem -LiteralPath $sourceRuntimeDir -File -Filter "cbm-ui-*.pack" |+ ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination $guardBundle }# Ownership is never inherited on Windows: descendants created under the# hardened root by an admin-group token can default to the Administrators# SID, while the exe policy demands the exact current user as owner. Stamp# the current SID explicitly on everything staged here.- foreach ($staged in @($guardBundle, $guardBin)) {+ $stagedRuntime = @($guardBundle) + @(Get-ChildItem -LiteralPath $guardBundle -File |+ ForEach-Object { $_.FullName })+ foreach ($staged in $stagedRuntime) {$stagedAcl = Get-Acl -LiteralPath $staged$stagedAcl.SetOwner($currentSid)Set-Acl -LiteralPath $staged -AclObject $stagedAcl@@ -155,9 +173,9 @@ try {$env:PYTHONUTF8 = "1" # encode argv/stdio as UTF-8# Green regression guards - must stay GREEN (exit 0). RED (exit 1) = the fix for-# the referenced issue regressed. The drive-picker guard needs the embedded HTTP-# UI (build target cbm-with-ui); against a non-UI binary it reports a precondition-# (exit 2) and is skipped rather than failed.+# the referenced issue regressed. The drive-picker guard needs the UI-enabled+# build and its external asset pack (target cbm-with-ui); against a non-UI+# binary it reports a precondition (exit 2) and is skipped rather than failed.$guards = @("tests\windows\test_non_ascii_path.py","tests\windows\test_non_ascii_cache_dump.py",@@ -168,6 +186,10 @@ $guards = @("tests\windows\test_cli_non_ascii_arg.py","tests\windows\test_windows_update_handoff.py")+$readinessGuard = "tests\test_daemon_open_readiness.py"+if (Get-ChildItem -LiteralPath $guardBundle -File -Filter "cbm-ui-*.pack") {+ $guards += $readinessGuard+}# Opt-in known-red repros - EXPECTED red (exit 1); never gate CI. Currently empty:# test_cli_non_ascii_arg.py was promoted to a guard when #423/#20's wide-argv fix landed.@@ -187,6 +209,13 @@ foreach ($t in $guards) {} elseif ($code -eq 1 -or $t -eq "tests\windows\test_windows_update_handoff.py") {Write-Host "RED ($t) - REGRESSION: a fixed Windows bug is broken again" -ForegroundColor Red$guardFailures += $t+ } elseif ($code -eq 2 -and $t -eq $readinessGuard) {+ # This guard must run against a UI runtime set built with TEST_SEAMS=1.+ # Treat a missing pack/seam as a broken gate, never a green precondition+ # skip; the workflow's guard build deliberately supplies both.+ Write-Host "FAILED ($t) exit=2 - UI readiness fixture is incomplete or lacks TEST_SEAMS=1" `+ -ForegroundColor Red+ $guardFailures += $t} elseif ($code -eq 2) {# Exit 2 is the guards' DOCUMENTED precondition-skip contract; every# other unexpected code (a crashed python, an access-violation status,diff --git a/scripts/test.sh b/scripts/test.shindex 46db34e5e..be3ced7ca 100755--- a/scripts/test.sh+++ b/scripts/test.sh@@ -14,7 +14,7 @@ Usage: scripts/test.sh [--suites LIST] [--arch ARCH] [VAR=VAL ...]The canonical test entry: identical in local CI, PR CI, dry run and release.DEFAULT (no --suites) is exactly what CI runs: static contract checks-(Step 0a-0j), a CLEAN sanitizer build, every suite via the parallel harness,+(Step 0a-0r), a CLEAN sanitizer build, every suite via the parallel harness,then the prod-binary regression guards (Steps 4-6).Modes:@@ -198,7 +198,7 @@ if [ -n "$SUITES" ]; thenfi# Step 0: fast build/security harness regressions run before the compiler-heavy-# suite. The Windows package surface is static here; native launcher behavior is+# suite. The Windows package surface is static here; native runtime behavior is# exercised by scripts/test-windows.ps1.echo "=== Step 0a: build directory safety contract ==="bash "$ROOT/tests/test_build_dir_safety.sh"@@ -212,7 +212,7 @@ bash "$ROOT/tests/test_ui_dev_proxy_security.sh"echo "=== Step 0d: daemon soak recovery contract ==="bash "$ROOT/tests/test_soak_daemon_recovery_contract.sh"-echo "=== Step 0e: Windows launcher bundle contract ==="+echo "=== Step 0e: Windows runtime bundle contract ==="bash "$ROOT/tests/test_windows_bundle_contract.sh"echo "=== Step 0f: tree-sitter runtime Makefile dependencies ==="@@ -236,6 +236,24 @@ bash "$ROOT/tests/test_spawn_no_window_contract.sh"echo "=== Step 0l: no embedded integration-script text (AV surface) ==="bash "$ROOT/tests/test_no_embedded_scripts_contract.sh"+echo "=== Step 0m: external UI asset-pack contract ==="+bash "$ROOT/tests/test_ui_asset_pack_contract.sh"++echo "=== Step 0n: complete vendored-integrity contract ==="+bash "$ROOT/tests/test_vendored_integrity_contract.sh"++echo "=== Step 0o: package runtime-asset retention contract ==="+bash "$ROOT/tests/test_package_runtime_assets_contract.sh"++echo "=== Step 0p: exact release archive extraction contract ==="+bash "$ROOT/tests/test_release_archive_extractor_contract.sh"++echo "=== Step 0q: exact-set VirusTotal gate contract ==="+bash "$ROOT/tests/test_vt_gate_zero_tolerance_contract.sh"++echo "=== Step 0r: VirusTotal release-note evidence contract ==="+bash "$ROOT/tests/test_vt_release_notes_contract.sh"+# Verify compiler supports target archverify_compiler "$CC"@@ -301,6 +319,20 @@ CBM_TEST_BINARY="$WATCHDOG_BINARY" bash "$ROOT/tests/test_worker_error_response.# skipping it silently would hide the gap. Run it by hand:# make -f Makefile.cbm cbm TEST_SEAMS=1 && bash tests/test_hook_conflict_notice.sh+# Step 5e: `daemon start --open` is the only UI startup operation that waits+# synchronously. Build the real product against a tiny deterministic external+# pack (no npm/network dependency) and prove it waits for the CBM HTTP root,+# rejects a foreign occupied port, and fails closed when the pack is missing.+# This runs here, after the other seam-bearing product guards, so every native+# local-CI leg exercises the exact executable behavior without lengthening the+# daemon's asynchronous startup critical path.+echo "=== Step 5e: daemon UI --open readiness ==="+make -j"$NPROC" -f Makefile.cbm cbm-with-ui TEST_SEAMS=1 \+ UI_ASSET_PREBUILT=1 UI_ASSET_DIST="$ROOT/tests/fixtures/ui-readiness" \+ UI_ASSET_MANIFEST="$BUILD_DIR/generated/ui_asset_readiness_manifest.c" \+ ${MAKE_ARGS[@]+"${MAKE_ARGS[@]}"}+python3 "$ROOT/tests/test_daemon_open_readiness.py" "$ROOT/$BUILD_DIR/codebase-memory-mcp"+# Step 6: security-strings URL allow-list regression. The MSYS2 CLANG64 toolchain# bakes its package-tracker URL into the static Windows .exe; the binary string# audit must allow-list it (Windows-only — Linux smoke never saw it).diff --git a/scripts/vendored-checksums.txt b/scripts/vendored-checksums.txtindex 1c9e71d85..6bc70f33b 100644--- a/scripts/vendored-checksums.txt+++ b/scripts/vendored-checksums.txt@@ -1,3 +1,978 @@+2e0110e07abef7c2548b26ec9d6969775617ca539a0dc8dbeeb14d6452c711d1 internal/cbm/vendored/common/LICENSE+a6d5c800517700f329b948e725feade008c2bc2ff006c258d962f558317c2a53 internal/cbm/vendored/common/scanner.h+91421857a1e4039c365f42221dd5243990b668c58932a2fe31d0f99b3d547b66 internal/cbm/vendored/common/tag.h+c5cfb43042b6b72045f4ba997834d0a7786d2793d91680868b5815b39f14fc78 internal/cbm/vendored/common/tree_sitter/LICENSE+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/common/tree_sitter/alloc.h+31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/common/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/common/tree_sitter/parser.h+351738d52ef14e574aa69d4a9b95f8d7b6eddc2658fef91bab95a72d00687b08 internal/cbm/vendored/grammars/MANIFEST.md+ad8425038de519f8c4e3e9339feebf99dfad8a6002dcf79227d91402780a32cc internal/cbm/vendored/grammars/ada/LICENSE+02805ec13939b749c891567be36bf024b09034e04c80683a1ae667272458d549 internal/cbm/vendored/grammars/ada/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/ada/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/ada/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/ada/tree_sitter/parser.h+ef120ea13e3e543234f3d9a193c99ea512872979802dc0cebaea404c1a47047c internal/cbm/vendored/grammars/agda/LICENSE+920b14e09681522ce169ff1f299a9d290253fd9363b7880df1d1ab7a40742664 internal/cbm/vendored/grammars/agda/parser.c+38dbda8f6e47d68cc0f556689618b028ebd34853ff96badb4af1c5d64939f75c internal/cbm/vendored/grammars/agda/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/agda/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/agda/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/agda/tree_sitter/parser.h+c3d045abbc0a8dec1b00737c0668f6dbb028d248521b74e79778c726671925ed internal/cbm/vendored/grammars/apex/LICENSE+e960fdd8672cea2a93887913017f231153695ca1778ffd3fcdfceac97ef6ffec internal/cbm/vendored/grammars/apex/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/apex/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/apex/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/apex/tree_sitter/parser.h+0e9f43573925c2e4b49f328a45c4df22c882191d77d876b0d18ecd60bd21e17c internal/cbm/vendored/grammars/assembly/LICENSE+dbcd8f007af7af67ef58bea0b1f7d3121902915df80ccce23588f0ac48438b35 internal/cbm/vendored/grammars/assembly/parser.c+253b44a7b4313a7afd0c505c2fc6e7ce4b8e78955ebf4be3ea000532ec060673 internal/cbm/vendored/grammars/assembly/tree_sitter/alloc.h+4ff743903dc46f5db6aa54f31c6b4d160a8a9779e5b2ab1ee59ae7ebcd850ea1 internal/cbm/vendored/grammars/assembly/tree_sitter/array.h+a3eb18ef034b3f4255b965a26caa276f9cfe13a79573b402f1a12dc5018052aa internal/cbm/vendored/grammars/assembly/tree_sitter/parser.h+9ec95a90150fa19e2cee78faf49138fc480f6f7a2354006a0ab150c44239447e internal/cbm/vendored/grammars/astro/LICENSE+4b3dd1aa7a0f31a71cd422c2815b4d60278db33dd62c55956ec2094d5d9cd98c internal/cbm/vendored/grammars/astro/parser.c+5dc28475917fe4b2cf38e74a6e6c71d26dc99eb31f6718c0a511188aab2fbea4 internal/cbm/vendored/grammars/astro/scanner.c+67b9e557aa5092a8719e16958a445b748f8168527715704209148d0d63797fc0 internal/cbm/vendored/grammars/astro/tag.h+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/astro/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/astro/tree_sitter/array.h+435ac887a97b4199fcf97707649aa987a94524f0e023f4e8287eae5dae49453f internal/cbm/vendored/grammars/astro/tree_sitter/parser.h+512d5f9072b6227e356c765b40a4194fda964f75095b0816f24ce75aa8df03fa internal/cbm/vendored/grammars/awk/LICENSE+b7df8791b6770f41e570bc31688c5bea6e514b77ff0b7d9abf875056fa09395b internal/cbm/vendored/grammars/awk/parser.c+f334ef81e9beaac0ee0bcb75aac97275012effe9d72c01fc1f858d3a1e6637a1 internal/cbm/vendored/grammars/awk/scanner.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/awk/tree_sitter/alloc.h+15624dcc418a19cf904a484af1950dbea9dec9097861ddf59d30c43805198efa internal/cbm/vendored/grammars/awk/tree_sitter/array.h+435ac887a97b4199fcf97707649aa987a94524f0e023f4e8287eae5dae49453f internal/cbm/vendored/grammars/awk/tree_sitter/parser.h+49bf33cf78ef5897e4e161ce1517df7de1ae5042a65b6bcfd44401e0fc606559 internal/cbm/vendored/grammars/bash/LICENSE+99e8f38f44f841984679aac9e709a2580755bfb81f8da7d5374a23b6b642565e internal/cbm/vendored/grammars/bash/parser.c+6155498e6152e9c27e9a0da66e99f2fbef72bd0c37d5c89a99e4d2a1d3a58257 internal/cbm/vendored/grammars/bash/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/bash/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/bash/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/bash/tree_sitter/parser.h+8976806a7d187d8e152d49146fae44d8a98bb15be05099e63843756c116efcf0 internal/cbm/vendored/grammars/beancount/LICENSE+2a22b435a88fc5c45b30288f5959cb26d128cca1c5e507a5fb9fcf0b4aa77527 internal/cbm/vendored/grammars/beancount/parser.c+66b85aef326a88190122522696c3785d426cdc424fea1dabeed376873f2b1822 internal/cbm/vendored/grammars/beancount/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/beancount/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/beancount/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/beancount/tree_sitter/parser.h+e4bfcc87169fdab12e351211541723132f58648a5ffad8f0f45b534349dbed45 internal/cbm/vendored/grammars/bibtex/LICENSE+87e9fca00404d2a30362ae9515d16d45474bea9ad8af461a1639a32bed059cd1 internal/cbm/vendored/grammars/bibtex/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/bibtex/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/bibtex/tree_sitter/array.h+fdc6c206253cee98e7ed2d32cf27c6497ec4de47aef2f630796f3d249bb5e447 internal/cbm/vendored/grammars/bibtex/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/bicep/LICENSE+388da6d03f7a16f9c2f530bd80af52de32a435af9b5968c92b64e2d6cb7a15e6 internal/cbm/vendored/grammars/bicep/parser.c+d558092e472fe737f5dde96fcdf15d61f4aaedd949fdc65ce3443f4b003bd209 internal/cbm/vendored/grammars/bicep/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/bicep/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/bicep/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/bicep/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/bitbake/LICENSE+df4a8540abd9d2c1bdcba78e28ed359f5c674262b75216a1b4f6effb582e8e57 internal/cbm/vendored/grammars/bitbake/parser.c+8e048c7f414d06ed25718843418f26b80a8dbb4316fd7cf236a1541fee0a104f internal/cbm/vendored/grammars/bitbake/scanner.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/bitbake/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/bitbake/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/bitbake/tree_sitter/parser.h+96e0c1803ffb831c7287b1fb7f88567d05e58d37da553e6bb9a9c4a765434ecb internal/cbm/vendored/grammars/blade/LICENSE+0e938a69b958e1af5a74aa7f735a5c5bd224c24c052b3ca95a5d99a3702c38bc internal/cbm/vendored/grammars/blade/parser.c+679b5d3f456b1bb44ab76a82088d4e86bcbba9d18b95d675836a37d23ed50ea3 internal/cbm/vendored/grammars/blade/scanner.c+9752fdd4f0eef3b6ad831d3e1d5ed5828971f557e73ae2c7afe926e9d87eba3e internal/cbm/vendored/grammars/blade/tag.h+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/blade/tree_sitter/alloc.h+db7d66e4305e3f37b5d31a3291acc01fed95054474a75b3c7cff72048ef9b797 internal/cbm/vendored/grammars/blade/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/blade/tree_sitter/parser.h+2e0110e07abef7c2548b26ec9d6969775617ca539a0dc8dbeeb14d6452c711d1 internal/cbm/vendored/grammars/c/LICENSE+66d6c76e7dc5c83ecb5b0ebf69050a7c227d35ee4d27b21dc252cc759f227d17 internal/cbm/vendored/grammars/c/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/c/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/c/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/c/tree_sitter/parser.h+778fb7d63b8c1844da315648c02f325c4713a6f4a5d19644fd413421422776d3 internal/cbm/vendored/grammars/c_sharp/LICENSE+720746e4d6bdbe1ba76f83a4c157a8ec3ce20c30a6b4744f30ca3993e55b8469 internal/cbm/vendored/grammars/c_sharp/parser.c+83dad602517523bc185e195d9446a92f73786364661bc87b564e5206ca52d6be internal/cbm/vendored/grammars/c_sharp/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/c_sharp/tree_sitter/alloc.h+8c814560c31d0157013bc3399a9282fc5049d06790a36f55115373d6c3abe16b internal/cbm/vendored/grammars/c_sharp/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/c_sharp/tree_sitter/parser.h+108bfb047e0d45962dcadedfce730c86c278bc2a67f6939df405a706bec27e20 internal/cbm/vendored/grammars/cairo/LICENSE+1631b184694158672da430675d3c3990c6db48eafb9e888b769866dc9be0092b internal/cbm/vendored/grammars/cairo/parser.c+681bd8135f2381810e4c15d6ff103622d1150e5ab9474d66b3b33a9c9a83fde2 internal/cbm/vendored/grammars/cairo/scanner.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/cairo/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/cairo/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/cairo/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/capnp/LICENSE+6f66b48753c76927f24df02195aae27e193f07ee8ee5b3e6cc5207c277d02a20 internal/cbm/vendored/grammars/capnp/parser.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/capnp/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/capnp/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/capnp/tree_sitter/parser.h+7e17ba5e26b0438ca04ebf2d9e7931da3080509da6625e117f6feb943ecf767a internal/cbm/vendored/grammars/cfml/LICENSE+490fa06668437e3731f5b8f4e01cb6a5c2a1c700befc2b7312a84e642e7c7371 internal/cbm/vendored/grammars/cfml/parser.c+d908e93380b7c692fd7e7b972961e582f238cc717330f001c3d4d9b40979853e internal/cbm/vendored/grammars/cfml/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/cfml/tree_sitter/alloc.h+31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/grammars/cfml/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/cfml/tree_sitter/parser.h+7e17ba5e26b0438ca04ebf2d9e7931da3080509da6625e117f6feb943ecf767a internal/cbm/vendored/grammars/cfscript/LICENSE+eeadc5447401a424faf2a9214727debb25a2c3f2b8315e43c86b6ed48bbb1290 internal/cbm/vendored/grammars/cfscript/parser.c+72cb7798ad9e91d30172aec210cbaf9fa30c9de2bc2f97160722dff1677ac405 internal/cbm/vendored/grammars/cfscript/scanner.c+693e1faede26577a2d07e2d2c04aa3ccd0cdee3969ec07d0cb2e382512e4840b internal/cbm/vendored/grammars/cfscript/tag.h+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/cfscript/tree_sitter/alloc.h+31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/grammars/cfscript/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/cfscript/tree_sitter/parser.h+a2010f343487d3f7618affe54f789f5487602331c0a8d03f49e9a7c547cf0499 internal/cbm/vendored/grammars/clojure/LICENSE+93e7bc5496b929e8627c95ec39fa78f267b084868f7ecc2ef34df00919eb9b06 internal/cbm/vendored/grammars/clojure/parser.c+435ac887a97b4199fcf97707649aa987a94524f0e023f4e8287eae5dae49453f internal/cbm/vendored/grammars/clojure/tree_sitter/parser.h+97334c0f9c0962b33cbe03223f584b8ed64c2d14419ce80cc2e945eb8d367d28 internal/cbm/vendored/grammars/cmake/LICENSE+daf550976dc40608917b1f16b5c8b21773111bdd2a7fcc23c5e5fec3737055f5 internal/cbm/vendored/grammars/cmake/parser.c+053daf0b9f96ea3542955ff57ce2e22b4cc6fce84494d2a376586e4d9b36826a internal/cbm/vendored/grammars/cmake/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/cmake/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/cmake/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/cmake/tree_sitter/parser.h+1f58f9911dc5e3bcb96de28bb28e7b6bb7eb323952d29569c5d7214a152146bb internal/cbm/vendored/grammars/cobol/LICENSE+d40a31d4854a2d82977c74d33c3ee9c004d9e63743176ebc84159a1734db7b2b internal/cbm/vendored/grammars/cobol/parser.c+0e146beb0331e4f95e2fb815e263c649f2bc404b35dd1b19eb125cbd4ed95df8 internal/cbm/vendored/grammars/cobol/scanner.c+8e819abdeba5866bf1aaf6e7b97522241c903d94a18395c6a75ed02984270ee8 internal/cbm/vendored/grammars/cobol/tree_sitter/parser.h+00bb7f417416e8233ae465209e72eaa6162d53b061add7d9bed0238552a6fa0c internal/cbm/vendored/grammars/commonlisp/LICENSE+27082ecef6f3fe6c09aaf2488b2003f031a165d23b15179ad6c2b52bf47b05ff internal/cbm/vendored/grammars/commonlisp/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/commonlisp/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/commonlisp/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/commonlisp/tree_sitter/parser.h+2e0110e07abef7c2548b26ec9d6969775617ca539a0dc8dbeeb14d6452c711d1 internal/cbm/vendored/grammars/cpp/LICENSE+74b2f2e7ce5d0fe7dfd850873c93326aea2b3b52ad4f5853b562235bab2a865e internal/cbm/vendored/grammars/cpp/parser.c+f12c62324060b8ac41eac74f3b1888830e31bbe8244bb7b013c2890867a7cc7b internal/cbm/vendored/grammars/cpp/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/cpp/tree_sitter/alloc.h+8c814560c31d0157013bc3399a9282fc5049d06790a36f55115373d6c3abe16b internal/cbm/vendored/grammars/cpp/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/cpp/tree_sitter/parser.h+d1e5e5f807a9e842c16a0b392d7dcc5542f9ed9163533fa7d9798f7289fa8547 internal/cbm/vendored/grammars/crystal/LICENSE+6d09d4d187c3189eed9475c9c6147b5ce5091cdfb97200d29cfc735bff15d319 internal/cbm/vendored/grammars/crystal/parser.c+73daf8e268278b9865dc39bccd9ce3ae6544ebb6d427087d80ef31fa6867058e internal/cbm/vendored/grammars/crystal/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/crystal/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/crystal/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/crystal/tree_sitter/parser.h+19bdea72076452c827a23882499de1820a8de6a49c0d7025cac642bf209748b9 internal/cbm/vendored/grammars/crystal/unicode.c+c5cfb43042b6b72045f4ba997834d0a7786d2793d91680868b5815b39f14fc78 internal/cbm/vendored/grammars/css/LICENSE+c4e32579521867dd2c3d3a812a963eb14c6585ac4f6e1fa519117fa552c59561 internal/cbm/vendored/grammars/css/parser.c+d489f81c0e41afc01f9e1f0c9710916b53ac7fdd501f63e2a027487ded8eba3f internal/cbm/vendored/grammars/css/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/css/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/css/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/css/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/csv/LICENSE+341940cee00f41588c509c88211a90b7846a1cc3d30731d711413146bfaf4964 internal/cbm/vendored/grammars/csv/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/csv/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/csv/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/csv/tree_sitter/parser.h+f44d7107a33801260dc82624c91a71ebf5918b4038a0fb0e3ef60e2dd9ba1999 internal/cbm/vendored/grammars/cuda/LICENSE+9e9c6db92de6cd42c481a9ed401afc7063000c8e9c1d01375b8680b10b5f9b24 internal/cbm/vendored/grammars/cuda/parser.c+165e42b87ac60a459e71d1aee5a42c3c0579f633b9ca1c8b0a37d4b2ca0b6e26 internal/cbm/vendored/grammars/cuda/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/cuda/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/cuda/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/cuda/tree_sitter/parser.h+ecf206b1a27e8e4ea07f1e1529cb111b4be5ce8420bd27b8269981d9c0c389f8 internal/cbm/vendored/grammars/d/LICENSE+223c7ff76843a5d2cd1d298def8f08cf5db7cdc5b6302b82766504970d2622a4 internal/cbm/vendored/grammars/d/parser.c+3aabb87f51afe6a96f4e695594c097a4f7f38301bf17f69d6b0fb0874b004427 internal/cbm/vendored/grammars/d/scanner.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/d/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/d/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/d/tree_sitter/parser.h+d270cb3a4985d75033bd77d875ccebff1d66e32788a3f727891e28d76132dd46 internal/cbm/vendored/grammars/dart/LICENSE+5ed597b41cbefcbad156157b7371618ca7073d69ea9b6c0e66a13379480efac8 internal/cbm/vendored/grammars/dart/parser.c+022804ce8d08550b7a86c44805cd4784db70124a1d7f5959ca819b3623a31e2b internal/cbm/vendored/grammars/dart/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/dart/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/dart/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/dart/tree_sitter/parser.h+b539c1b4ccd868c8d4fc89651c8133a1678823f5057e2e1a81455a3df4f4c0b8 internal/cbm/vendored/grammars/devicetree/LICENSE+f34c96602799bacba5ca42b3d0e11c5e76896d4eef4dd589cc1fa583e1adb2eb internal/cbm/vendored/grammars/devicetree/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/devicetree/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/devicetree/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/devicetree/tree_sitter/parser.h+bb98faf5a86e9458536a6c745e02b53775d01066f1e51dda4ae220a3c0b050f4 internal/cbm/vendored/grammars/diff/LICENSE+982e2643fd4ebc139086152e03191af088b07b4cf7995d3c5519d1791285ca32 internal/cbm/vendored/grammars/diff/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/diff/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/diff/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/diff/tree_sitter/parser.h+806b8fcd19c1cdf23e178eb25942acc844a38669e36b2c896c7baf5f8bcecbb4 internal/cbm/vendored/grammars/dockerfile/LICENSE+7a5f1596a1efb20b9580f8272998ec7d2d2b24d93e2e9b61bc8a686268af95d9 internal/cbm/vendored/grammars/dockerfile/parser.c+6a115142b6d5fa2d77fe2b287c40a6ff971c1ad9a24b01275af9e0cedf50b58b internal/cbm/vendored/grammars/dockerfile/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/dockerfile/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/dockerfile/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/dockerfile/tree_sitter/parser.h+117a35332cc959aea7d16cfa7427f097f7fcfff6b4ef16b14a91a7296f3897dc internal/cbm/vendored/grammars/dotenv/LICENSE+e5b56544809c602ce8443c46eee473edd95d61fc92517324fd231a0b44441cdb internal/cbm/vendored/grammars/dotenv/parser.c+07662a41007a64798d9b9c8ba9eff3ed5e1d776ba7b99951b2ceba6785953cc3 internal/cbm/vendored/grammars/dotenv/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/dotenv/tree_sitter/alloc.h+31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/grammars/dotenv/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/dotenv/tree_sitter/parser.h+f7d440114acea14bf9f510bb2e4b93f2aac6a51baf271acc112009b9b2ebe55e internal/cbm/vendored/grammars/elisp/LICENSE+1cc65a8ef1fc0d284db596e6ac5da003adef982659462ab686422c19d068b76e internal/cbm/vendored/grammars/elisp/parser.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/elisp/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/elisp/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/elisp/tree_sitter/parser.h+a6cba85bc92e0cff7a450b1d873c0eaa2e9fc96bf472df0247a26bec77bf3ff9 internal/cbm/vendored/grammars/elixir/LICENSE+e3c05b99c0b995f6387c87276247511226a307016f3d9f3f3a3b848d954919ab internal/cbm/vendored/grammars/elixir/parser.c+c6f6feb0f08627e920f8f299a2f5968265daa2c389182232a1205038713ef3a4 internal/cbm/vendored/grammars/elixir/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/elixir/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/elixir/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/elixir/tree_sitter/parser.h+26f7bf09693dd895ea64777316bad0133b131a8478a660b4785d4b9d1322f9a1 internal/cbm/vendored/grammars/elm/LICENSE+a86ae12749c2051bbabd34e82e5d4675816f1357e68ab8108db36ea1af0d56c3 internal/cbm/vendored/grammars/elm/parser.c+7f7434ed66f621072d089741a78b5d91bd51cbedc46e618039d2e2a039df4784 internal/cbm/vendored/grammars/elm/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/elm/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/elm/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/elm/tree_sitter/parser.h+c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 internal/cbm/vendored/grammars/erlang/LICENSE+66d6160f3d5abdee2f55b0331f6446b3b71b7530bf7aa021ecfff85a2a3e7006 internal/cbm/vendored/grammars/erlang/parser.c+41d3fcc8b045c7cfb8a368ccb928de0514bd1a09080dc9fd499781f3a17e1ed2 internal/cbm/vendored/grammars/erlang/scanner.c+5267878183423ca66ee48930d0c157d1c40dddd9fd792eb33130c2e83e522796 internal/cbm/vendored/grammars/erlang/tree_sitter/alloc.h+547bec1c0112c05ddba8985719cbd72dd3dbfd0a721b958c07f448e2f98ae68c internal/cbm/vendored/grammars/erlang/tree_sitter/array.h+fcbda101909b47c29bea096797235dab02897d59c0ba85903cb84afa02f86c8f internal/cbm/vendored/grammars/erlang/tree_sitter/parser.h+a2010f343487d3f7618affe54f789f5487602331c0a8d03f49e9a7c547cf0499 internal/cbm/vendored/grammars/fennel/LICENSE+11f7789f54d3d7905e995a9a4bf14dce5a7a1654b3d7c17657e7fc392334cc42 internal/cbm/vendored/grammars/fennel/parser.c+ab104936984904469572a4e868149f7a22fb2929347f837ae6a1f9b790f1b173 internal/cbm/vendored/grammars/fennel/tree_sitter/parser.h+6b0382b16279f26ff69014300541967a356a666eb0b91b422f6862f6b7dad17e internal/cbm/vendored/grammars/fish/LICENSE+046d60eada47aec59beb0d614c1062f613fc6b5011a374487bdc84fb6c03eb54 internal/cbm/vendored/grammars/fish/parser.c+3fe4381f7d49edccd748efe38835f794427db53f0d45e4d0c590368e88eedea5 internal/cbm/vendored/grammars/fish/scanner.c+df898ca6d3eb880b9fdf7d3179363d7657abcd4b0a0565d8fd6b47215d8cc149 internal/cbm/vendored/grammars/fish/tree_sitter/parser.h+1f58f9911dc5e3bcb96de28bb28e7b6bb7eb323952d29569c5d7214a152146bb internal/cbm/vendored/grammars/form/LICENSE+53afbc816aebdf5d79365b41a3025c5b254122a36ff5177a8b50fb81ea7a9a24 internal/cbm/vendored/grammars/form/parser.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/form/tree_sitter/alloc.h+31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/grammars/form/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/form/tree_sitter/parser.h+c0fc02a86ae2b179c4729694c523bbf42da674e5136ed8e12e3cb2f26556ea9f internal/cbm/vendored/grammars/fortran/LICENSE+8be2e4ab88dde26cbb03cbf9de4fed2a7149fbbc65574fd53420e6d35980a244 internal/cbm/vendored/grammars/fortran/parser.c+ce4d30565ade37f2c6547cc302561e247a5616fa7564aa2bd057fde609a11134 internal/cbm/vendored/grammars/fortran/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/fortran/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/fortran/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/fortran/tree_sitter/parser.h+f9352b63e87252b282b252bf27530027c8ca69829e0023f8b8b682a736f271fd internal/cbm/vendored/grammars/fsharp/LICENSE+6339b7b3456e53288737f5b4b736877a3886b660fe8aca4a38ded6165d419577 internal/cbm/vendored/grammars/fsharp/common/scanner.h+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/fsharp/common/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/fsharp/common/tree_sitter/array.h+11b654fbba7770b1c710cc14b169be2deb5d89c0f87233d4605037c26c1ff657 internal/cbm/vendored/grammars/fsharp/common/tree_sitter/parser.h+52c664697fd20e7c42270868b68c648bc7633c9ced4642004292c984bd11154f internal/cbm/vendored/grammars/fsharp/parser.c+8129825c87805d079384dd486ebddc4fd382ffe0a150cc51f9fa252f6ad9627c internal/cbm/vendored/grammars/fsharp/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/fsharp/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/fsharp/tree_sitter/array.h+11b654fbba7770b1c710cc14b169be2deb5d89c0f87233d4605037c26c1ff657 internal/cbm/vendored/grammars/fsharp/tree_sitter/parser.h+8193651e765c9c23b0259b508320925dfbd99418aa424105b622b7787c2f01c5 internal/cbm/vendored/grammars/func/LICENSE+9a8db876c2689743a43556f48faf8cff14dcbc2e2aecc6051b02416fa73d007e internal/cbm/vendored/grammars/func/parser.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/func/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/func/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/func/tree_sitter/parser.h+d724405ce238a22c0d35769c5a36b386ad5958192efe8bbb304fb2896254575f internal/cbm/vendored/grammars/gdscript/LICENSE+3a96a4bd6738b9bebfda3298f429fa6cf1de251475ff01eb933ba2c06ba63003 internal/cbm/vendored/grammars/gdscript/parser.c+3740b77469aa649b2231bf6951ed5fbb04394595d1e599ab30f0e8338687fb49 internal/cbm/vendored/grammars/gdscript/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/gdscript/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/gdscript/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/gdscript/tree_sitter/parser.h+413ec4c3842f95bcaf662aba7d646b22baf044aa6ac5efa6531b94d4ee00248b internal/cbm/vendored/grammars/gitattributes/LICENSE+7e04344d54ca7b15ac67c4c328fa668f94bed85637b327bc9cb6580481aaef80 internal/cbm/vendored/grammars/gitattributes/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/gitattributes/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/gitattributes/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/gitattributes/tree_sitter/parser.h+239b228dfcf83043b3be6afe8c7508bbbecff75e8fe1e66db020ed21e213e721 internal/cbm/vendored/grammars/gitignore/LICENSE+8625bc1e752c2f612d1f80d8771e64c3d7472cfd9adeb27a0bc74233d8ca5f40 internal/cbm/vendored/grammars/gitignore/parser.c+f12bc72ed6061c957569298f2efe2f237a900fef9f06a2e527e381345f83d797 internal/cbm/vendored/grammars/gitignore/tree_sitter/parser.h+cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 internal/cbm/vendored/grammars/gleam/LICENSE+fd978350b0e5b644b8ada56247172da7f08d0204cb9cfba5680f12be53f81016 internal/cbm/vendored/grammars/gleam/parser.c+f9bda67b72b777e7ef3f3deeee4756a268624bdac7fd7a4a387c50f887c72351 internal/cbm/vendored/grammars/gleam/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/gleam/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/gleam/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/gleam/tree_sitter/parser.h+f44d7107a33801260dc82624c91a71ebf5918b4038a0fb0e3ef60e2dd9ba1999 internal/cbm/vendored/grammars/glsl/LICENSE+743b397ea43b0567d35a0c2dd29082718e4388d1e898a818693f2f80996fff2a internal/cbm/vendored/grammars/glsl/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/glsl/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/glsl/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/glsl/tree_sitter/parser.h+9cd353e181337293bdfaffdeb0dd784aa11dd28947fb5877d6e46fe8cd0efdfc internal/cbm/vendored/grammars/glsl/tree_sitter/runtime.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/gn/LICENSE+df4aa8df58a630a008008dc6cb90dc4b93998861d8b1db22c889e5709b3580af internal/cbm/vendored/grammars/gn/parser.c+122df4640dd1789a0a46b618a2d8b1d84c133421e45dbe7aa781ef8ef778cf6e internal/cbm/vendored/grammars/gn/scanner.c+b54bd3b3a5a6388c3993c0a0f487d4c4887a005d2bd9350e75c03af3066d4059 internal/cbm/vendored/grammars/gn/tree_sitter/parser.h+2e0110e07abef7c2548b26ec9d6969775617ca539a0dc8dbeeb14d6452c711d1 internal/cbm/vendored/grammars/go/LICENSE+7c10e2aad3b6c10cfdbfa917a2c371941e6eae5ecd21d04388eac89ed894681c internal/cbm/vendored/grammars/go/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/go/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/go/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/go/tree_sitter/parser.h+806b8fcd19c1cdf23e178eb25942acc844a38669e36b2c896c7baf5f8bcecbb4 internal/cbm/vendored/grammars/gomod/LICENSE+88320151bb3afb7513af5f0fdd4df961683b59f6f7273913e7ccbcfd167243e5 internal/cbm/vendored/grammars/gomod/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/gomod/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/gomod/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/gomod/tree_sitter/parser.h+44ee910db99318d5d0b74b0d187ab2c8cbc411ca0be632ad9300e54036a9d822 internal/cbm/vendored/grammars/gotemplate/LICENSE+dcb0a05fa2392506b37de33620e7d81d20fa4870a0c0356df3a8196c200572b6 internal/cbm/vendored/grammars/gotemplate/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/gotemplate/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/gotemplate/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/gotemplate/tree_sitter/parser.h+7bd2788c7154b102cf03eeb335faba32d897fb82f252b28663c16c76738aaba5 internal/cbm/vendored/grammars/graphql/LICENSE+7c7a2201b68c6ef26df7aa3b69db4927d0755797c7f0cc555d2f0a861c0823dc internal/cbm/vendored/grammars/graphql/parser.c+5bc67343c2bbda4e515ce1b90db08efe983f1ae1f97bf61d67b282dad5346a04 internal/cbm/vendored/grammars/graphql/tree_sitter/parser.h+5f10fff4ea3c4892af1e2f1af0b9ba7fa79843598808a1dbbbbc8231ca81d1ad internal/cbm/vendored/grammars/groovy/LICENSE+1f4f29eda27085e5b25f4c4957579d5e5fbc8e3318f0517a8636b713f301e4a0 internal/cbm/vendored/grammars/groovy/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/groovy/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/groovy/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/groovy/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/hare/LICENSE+bb6111e9f89cde51262d132b9d4ca57b012a20b990102744886e6fa0aaae742d internal/cbm/vendored/grammars/hare/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/hare/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/hare/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/hare/tree_sitter/parser.h+2e0110e07abef7c2548b26ec9d6969775617ca539a0dc8dbeeb14d6452c711d1 internal/cbm/vendored/grammars/haskell/LICENSE+a0f269377b61613f0f90b11126d03661fff08a1bbb808e0a3d5c477b6c9041fc internal/cbm/vendored/grammars/haskell/parser.c+2895fbd5518cffa672d42dda7ba030add2ec4b4280de7befe61edf2cf6447dea internal/cbm/vendored/grammars/haskell/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/haskell/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/haskell/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/haskell/tree_sitter/parser.h+5dc193ae6173ddeeb9d0d724cad043b7299353c0edeff125059df1ccb0b685e5 internal/cbm/vendored/grammars/haskell/unicode.h+c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 internal/cbm/vendored/grammars/hcl/LICENSE+3bbced5310cd21649414ff78fc801234f4e222f5e347ec55212909273558c707 internal/cbm/vendored/grammars/hcl/parser.c+2a5665e741d7dc30c2eb207f24931c954a7602ce1c28fdcccddaee1cb54aa0b9 internal/cbm/vendored/grammars/hcl/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/hcl/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/hcl/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/hcl/tree_sitter/parser.h+dec735ccc031754dd05e6556dd9e959915eb367cf01cf009c77a1a38786932b1 internal/cbm/vendored/grammars/hlsl/LICENSE+16f8be2de15d609e21e4cba1c1acd591a909803b64169060d64f6a3a800b205c internal/cbm/vendored/grammars/hlsl/parser.c+0ce98524475f4050723d1becaae51c33438bf30414d5bf5e2c2e8514763a78ec internal/cbm/vendored/grammars/hlsl/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/hlsl/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/hlsl/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/hlsl/tree_sitter/parser.h+9cd353e181337293bdfaffdeb0dd784aa11dd28947fb5877d6e46fe8cd0efdfc internal/cbm/vendored/grammars/hlsl/tree_sitter/runtime.h+2e0110e07abef7c2548b26ec9d6969775617ca539a0dc8dbeeb14d6452c711d1 internal/cbm/vendored/grammars/html/LICENSE+b215854df96b3e8b3395785ba76b29f14829a8247e7618bc5cbe86b0681f326a internal/cbm/vendored/grammars/html/parser.c+1d3b0748ad4151e890188a71d8fdacb1162db78285e95258fd45b8b76b8c6521 internal/cbm/vendored/grammars/html/scanner.c+aaf1a10c8a2f685ef51a4aa6c01a2cbe166bff67eeccf6b9501a625b71f9ab70 internal/cbm/vendored/grammars/html/tag.h+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/html/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/html/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/html/tree_sitter/parser.h+4ea4f76b4942edcbac34ea41d6cb988ef8dcccd18117a179430cc7b2e3624807 internal/cbm/vendored/grammars/hyprlang/LICENSE+762e9ce4a39a0b26bd7d5efd9e418009a9a8d4f7b9232c98bd613ac2b8831074 internal/cbm/vendored/grammars/hyprlang/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/hyprlang/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/hyprlang/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/hyprlang/tree_sitter/parser.h+c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 internal/cbm/vendored/grammars/ini/LICENSE+dd96baa167a9be3beeb80cf74a31132676189417587ac7299f0f150c2acaaf7a internal/cbm/vendored/grammars/ini/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/ini/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/ini/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/ini/tree_sitter/parser.h+a1f7bdd70d68ab4e4adeb135b11cfa1696abf573c14495fb883a54f5d7968d0a internal/cbm/vendored/grammars/ispc/LICENSE+7653d173019aeebad726283f373ded75e417b68669feb8dae7430d5a6bb0978b internal/cbm/vendored/grammars/ispc/parser.c+b54bd3b3a5a6388c3993c0a0f487d4c4887a005d2bd9350e75c03af3066d4059 internal/cbm/vendored/grammars/ispc/tree_sitter/parser.h+1f58f9911dc5e3bcb96de28bb28e7b6bb7eb323952d29569c5d7214a152146bb internal/cbm/vendored/grammars/janet/LICENSE+1f31888821c64231a32b9414b4e94a5c726c01abfaeb1e4b4b2c5010d96eff7e internal/cbm/vendored/grammars/janet/parser.c+1f3c7ba502002d0ea9af0c132763473dd474e485c6d8ed246694f5f8a90b3d6f internal/cbm/vendored/grammars/janet/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/janet/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/janet/tree_sitter/array.h+11b654fbba7770b1c710cc14b169be2deb5d89c0f87233d4605037c26c1ff657 internal/cbm/vendored/grammars/janet/tree_sitter/parser.h+52ed137b039cd9c46409bc22e89938af911c95b157feae2d040b51e6084369a7 internal/cbm/vendored/grammars/java/LICENSE+4f2840f53db465aba32162158c6b41e9a9ea0e0b0b6e7a1377fcbef9ffc943e6 internal/cbm/vendored/grammars/java/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/java/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/java/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/java/tree_sitter/parser.h+2e0110e07abef7c2548b26ec9d6969775617ca539a0dc8dbeeb14d6452c711d1 internal/cbm/vendored/grammars/javascript/LICENSE+5bfb18365de4d5ff04a3a0d2ff8e5379d1a5c2a94f3b7b4622eea6886975215a internal/cbm/vendored/grammars/javascript/parser.c+1a5ab5c7a9a75d78d1bd36856e01efb186b2f4f6a261947bbb733aa4878b09b2 internal/cbm/vendored/grammars/javascript/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/javascript/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/javascript/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/javascript/tree_sitter/parser.h+9a204f0ddf288ec72bc40d593faee33c8ac1f4aed518dc80f9b77e03b0f6cbf3 internal/cbm/vendored/grammars/jinja2/LICENSE+49e2d8ce7e3de263a5b2c7b7c6e146476a201cb77f61a216ad06dc32d1d8b22d internal/cbm/vendored/grammars/jinja2/parser.c+ab104936984904469572a4e868149f7a22fb2929347f837ae6a1f9b790f1b173 internal/cbm/vendored/grammars/jinja2/tree_sitter/parser.h+ffaefecad68467134f8c701120a2410a2384ffff7a605b63638cf0b51e7d16cc internal/cbm/vendored/grammars/jsdoc/LICENSE+73259308d8def4adcdf76b628357a56f6575fa9c359bdf14e8f15a59a5fca28b internal/cbm/vendored/grammars/jsdoc/parser.c+756fbacfade9af6b773802aa4d22b0087e9a9ff8de6530ea81639bc442eab60a internal/cbm/vendored/grammars/jsdoc/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/jsdoc/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/jsdoc/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/jsdoc/tree_sitter/parser.h+2e0110e07abef7c2548b26ec9d6969775617ca539a0dc8dbeeb14d6452c711d1 internal/cbm/vendored/grammars/json/LICENSE+adacee38a7abef27eecd08d2815263ab6844de5057e15fa5cb3f9069e9e15313 internal/cbm/vendored/grammars/json/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/json/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/json/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/json/tree_sitter/parser.h+c91845be8393ab50c602041e1b1e96994ad40a1d28fec9b9ee3ffe0933e4e641 internal/cbm/vendored/grammars/json5/LICENSE+a0eb71abd5be3c0f190d7b074e4d9f5da94785307602d0ff07e17896fa29666e internal/cbm/vendored/grammars/json5/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/json5/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/json5/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/json5/tree_sitter/parser.h+9255998527012c182050a5bdb9ce619176f96bbeb2a056c3ba939011f85da611 internal/cbm/vendored/grammars/jsonnet/LICENSE+11705370b4ba242003aa47468977d842abd4ec49ef7ee0112957c617737c7964 internal/cbm/vendored/grammars/jsonnet/parser.c+aefbc834d85dae403669b9f9e435587e6ff5d5f5fcdaafaa430a864e5370f648 internal/cbm/vendored/grammars/jsonnet/scanner.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/jsonnet/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/jsonnet/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/jsonnet/tree_sitter/parser.h+74f800107f200f4e28da33e9c3f86230d37d8f4c0a4916f7111e800c395ee3a2 internal/cbm/vendored/grammars/julia/LICENSE+59ae648a7fe7904e350d2bedf12e27ce421b7d19483d2a6081fbea5f93e5827e internal/cbm/vendored/grammars/julia/parser.c+e4a923c06c0f3ccc89483f39a84f1a351f166aa45b07906c7de5c776fc7c9c92 internal/cbm/vendored/grammars/julia/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/julia/tree_sitter/alloc.h+db7d66e4305e3f37b5d31a3291acc01fed95054474a75b3c7cff72048ef9b797 internal/cbm/vendored/grammars/julia/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/julia/tree_sitter/parser.h+c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 internal/cbm/vendored/grammars/just/LICENSE+d0028b6605db1d568957e38e025a3126e88476bff1e88b0278b0c724214583b5 internal/cbm/vendored/grammars/just/parser.c+99a4ae2ff08e90a18d21fc42d324411aa0df57ebf486e06e70c0b5dd26d489e8 internal/cbm/vendored/grammars/just/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/just/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/just/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/just/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/kconfig/LICENSE+9eafe6e0ca00284500a239fe42af1a646c3809d06a192edee0d1c677e7708af9 internal/cbm/vendored/grammars/kconfig/parser.c+ab8d61735ded2a3220289266d115037e4c85779bb5f0b0a05e644f752a10d87f internal/cbm/vendored/grammars/kconfig/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/kconfig/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/kconfig/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/kconfig/tree_sitter/parser.h+b193808d3a13d34ec589a2c0bc2959f52a57f8fb1fc234d04ff8d87ac075864a internal/cbm/vendored/grammars/kdl/LICENSE+1d93da1d2d182c939dc31cec444bc50019c649bc4a47ba7a5b83a9881c72a30e internal/cbm/vendored/grammars/kdl/parser.c+6490bcefb45238524784da8ef6b317f3ddf7388bd4f197e4da446db8b76374bd internal/cbm/vendored/grammars/kdl/scanner.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/kdl/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/kdl/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/kdl/tree_sitter/parser.h+948495f61768f7de26bcc61113d8cd95f50bbc15adb678c28c941c6c8fcd5903 internal/cbm/vendored/grammars/kotlin/LICENSE+a9833ef20a6d907c09318207f6d1d699ccc075dd06f956995e3b534db57c0a93 internal/cbm/vendored/grammars/kotlin/parser.c+5971b53cb2b3976abd958ab75dfe3ecf81a36861d4bf743d8120ec797a34cdde internal/cbm/vendored/grammars/kotlin/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/kotlin/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/kotlin/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/kotlin/tree_sitter/parser.h+30dcd1c85faa36ad0917120a4d67a859e99f2dd8ff544cfc74c17f8b0b3ad06f internal/cbm/vendored/grammars/lean/LICENSE+9a1652cf2bfafdaf1b17d103cecd3255170748720abef08e05edddb45630e8a3 internal/cbm/vendored/grammars/lean/parser.c+804c60ee01f44d3d297cfb2555dbcc9dd02cc2508e4d63c947162fb789cfe465 internal/cbm/vendored/grammars/lean/scanner.c+ab104936984904469572a4e868149f7a22fb2929347f837ae6a1f9b790f1b173 internal/cbm/vendored/grammars/lean/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/linkerscript/LICENSE+2abb27b6165025bc4da386b131032ea292e8109d7beffa3e5c59b71926da8483 internal/cbm/vendored/grammars/linkerscript/parser.c+b54bd3b3a5a6388c3993c0a0f487d4c4887a005d2bd9350e75c03af3066d4059 internal/cbm/vendored/grammars/linkerscript/tree_sitter/parser.h+3b3e4e4252d5d7d1c18e1257005f23242bf0580ad619204fd093c99b8c56748d internal/cbm/vendored/grammars/liquid/LICENSE+a46c7ac9c8e79b6ee8bf234ea795d2388f0af5e47ef659ab6ff7a16284e2439d internal/cbm/vendored/grammars/liquid/parser.c+ebd07cf91d3924a16ab3b52073a64568dfc72ae466a9e6c59d76847dbd0c0181 internal/cbm/vendored/grammars/liquid/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/liquid/tree_sitter/alloc.h+8c814560c31d0157013bc3399a9282fc5049d06790a36f55115373d6c3abe16b internal/cbm/vendored/grammars/liquid/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/liquid/tree_sitter/parser.h+a292ff39c53d0d2af3a0804ec291737508f1c888efb148f8f2bd3030e7cfdc48 internal/cbm/vendored/grammars/llvm/LICENSE+f5c9f44d2e6d88769846bbc6367ccf068a64e0460f04a8ee8ae4042cb8d0f35f internal/cbm/vendored/grammars/llvm/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/llvm/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/llvm/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/llvm/tree_sitter/parser.h+9a32b02e4c917b1ce6b5e79d8ea81e25cefd7f27d89c7235f2afb262c06cf32e internal/cbm/vendored/grammars/lua/LICENSE+8ba69fc2db112b1994b32fdb6d97377c2c039fae3321a8ff8d6a9a6811c1c267 internal/cbm/vendored/grammars/lua/parser.c+d323b406438786487caab5018366a3a211176ab593d978509814de3f6cd49262 internal/cbm/vendored/grammars/lua/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/lua/tree_sitter/alloc.h+db7d66e4305e3f37b5d31a3291acc01fed95054474a75b3c7cff72048ef9b797 internal/cbm/vendored/grammars/lua/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/lua/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/luau/LICENSE+b5e6763944b2cb9c84fd6d5aa81b5a7fedf0f80dc39f6c3251199061bd14b4ac internal/cbm/vendored/grammars/luau/parser.c+6052a00f8056968bf06f7b464fd96d74b0081529e3901d697de4a96832ed4fa0 internal/cbm/vendored/grammars/luau/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/luau/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/luau/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/luau/tree_sitter/parser.h+1f58f9911dc5e3bcb96de28bb28e7b6bb7eb323952d29569c5d7214a152146bb internal/cbm/vendored/grammars/magma/LICENSE+29c2fea83f844cebbcacfdce57d9af56fa7c9bc7834f37e58a673bec34aa293e internal/cbm/vendored/grammars/magma/parser.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/magma/tree_sitter/alloc.h+31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/grammars/magma/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/magma/tree_sitter/parser.h+28eecdb75b6de2d9020603531461444bf54db827ee2fb345a8fcf4dbee7c2ad1 internal/cbm/vendored/grammars/make/LICENSE+822d9459a63d6fb1c504026066dcce1a0e6671aed24192df1dcf2460fe5774c0 internal/cbm/vendored/grammars/make/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/make/tree_sitter/alloc.h+db7d66e4305e3f37b5d31a3291acc01fed95054474a75b3c7cff72048ef9b797 internal/cbm/vendored/grammars/make/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/make/tree_sitter/parser.h+52ec8a1bf8256511e2a92613e0bb41ffefba3897f16fa958d7bb28c466dd4804 internal/cbm/vendored/grammars/markdown/LICENSE+ddbc1299b0970036167b9fd5335392b9650231bf04fee3f5807f1e8c0868a701 internal/cbm/vendored/grammars/markdown/parser.c+35d427cc00340ba556157f79841ab5fc6dc9e7f0f732f27a0593b43a4f3a6e00 internal/cbm/vendored/grammars/markdown/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/markdown/tree_sitter/alloc.h+db7d66e4305e3f37b5d31a3291acc01fed95054474a75b3c7cff72048ef9b797 internal/cbm/vendored/grammars/markdown/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/markdown/tree_sitter/parser.h+8673f5acd59bfb3bd129760a57f72092d5e3c01e05837532eac9497cf8006a46 internal/cbm/vendored/grammars/matlab/LICENSE+f9d5847b7e4f147ae68160761ef5997d5e67a676a1a2584f428a45ff9d23280f internal/cbm/vendored/grammars/matlab/parser.c+b2bf16c36f014d5b85e57cf6eefba4c151b0af2e80510139040f5889be82b821 internal/cbm/vendored/grammars/matlab/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/matlab/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/matlab/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/matlab/tree_sitter/parser.h+40e46efcec726e70cc95c553ac377674f0a5d2eec6089483ba237af7dae4c54c internal/cbm/vendored/grammars/mermaid/LICENSE+096962c8a1d325690882c9461fb63712007698130ef1e1c1b9d974b147c94d33 internal/cbm/vendored/grammars/mermaid/parser.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/mermaid/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/mermaid/tree_sitter/array.h+435ac887a97b4199fcf97707649aa987a94524f0e023f4e8287eae5dae49453f internal/cbm/vendored/grammars/mermaid/tree_sitter/parser.h+62bca3ac5aaf95fdebc7f3d22f061dfa2fabd069c21b89cf18f704ef428f92b9 internal/cbm/vendored/grammars/meson/LICENSE+4a5e759ba9e7bc9d8b62db302ee4bc91bcb9a9421c3a61f56a263a2ce6cdf5bf internal/cbm/vendored/grammars/meson/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/meson/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/meson/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/meson/tree_sitter/parser.h+d724405ce238a22c0d35769c5a36b386ad5958192efe8bbb304fb2896254575f internal/cbm/vendored/grammars/mojo/LICENSE+0a42ee50e3d60b705c0ba955fc2c3e92b96cfea7b09a3fd0fc86e9bc259aa488 internal/cbm/vendored/grammars/mojo/parser.c+3f8067d2dd802c0e51e6bd2b8f2ec86a4a2f5b8284bd6f0f543b0c962d61e48b internal/cbm/vendored/grammars/mojo/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/mojo/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/mojo/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/mojo/tree_sitter/parser.h+9d65ce763fc8041bf860b52fe8e2e91bad4034deb1d93fe8a303f31b3217ecc0 internal/cbm/vendored/grammars/move/LICENSE+49dba78c5d151b55d6589c2909dff17e9981463f56620165ca4fc4bda6402120 internal/cbm/vendored/grammars/move/parser.c+ab104936984904469572a4e868149f7a22fb2929347f837ae6a1f9b790f1b173 internal/cbm/vendored/grammars/move/tree_sitter/parser.h+d6e36f2e5d337e6f72ea697a9675ed97fc53daf04522682d6f8db316b0e5b472 internal/cbm/vendored/grammars/nasm/LICENSE+2f5d5a583d9da8752b55604e8e0c1c217e3a9dcadfffc0032fe44a5480fad8c4 internal/cbm/vendored/grammars/nasm/parser.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/nasm/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/nasm/tree_sitter/array.h+df898ca6d3eb880b9fdf7d3179363d7657abcd4b0a0565d8fd6b47215d8cc149 internal/cbm/vendored/grammars/nasm/tree_sitter/parser.h+39313c75af91e581acd59f2c43a94d6216ce52e76f65125a1bd8e900f6f548a5 internal/cbm/vendored/grammars/nickel/LICENSE+926d0643f61cadba0ec6adecadef40b226da42100306b8b36e0c5aaaa40064c3 internal/cbm/vendored/grammars/nickel/parser.c+db299f4dedebe72f4596e2bba26cf857737e5a6699a81d94aadbb1ab09656422 internal/cbm/vendored/grammars/nickel/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/nickel/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/nickel/tree_sitter/array.h+fdc6c206253cee98e7ed2d32cf27c6497ec4de47aef2f630796f3d249bb5e447 internal/cbm/vendored/grammars/nickel/tree_sitter/parser.h+c1b72e50266464ec5118d26200e17bf1f472d142e62ab637e1ffc23986657a78 internal/cbm/vendored/grammars/nix/LICENSE+00f20f027b6bfc56bc309e2644709d6ca4341d40dc5dca382759b112cf850b95 internal/cbm/vendored/grammars/nix/parser.c+c5fa4d1d5820cc59f39cb3cb9a9a171e5144b2f63d285cf3450be0a8e549ede8 internal/cbm/vendored/grammars/nix/scanner.c+435ac887a97b4199fcf97707649aa987a94524f0e023f4e8287eae5dae49453f internal/cbm/vendored/grammars/nix/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/objc/LICENSE+9b7be0223aa2612da3fa646b1ff9d77f5b70f03cd7d231658216e79d5d49c6bf internal/cbm/vendored/grammars/objc/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/objc/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/objc/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/objc/tree_sitter/parser.h+85b458dc150c4d17873dd5e73d01cfa23c797997a09d841884e08378242e929c internal/cbm/vendored/grammars/objectscript_routine/LICENSE+f3a047fba6d238da258c0370878e703504b347aad13add09a021935daa891bd3 internal/cbm/vendored/grammars/objectscript_routine/objectscript_common.h+fb9320a77f7c3c110540e9a569c2a8dd7ff74784ae05aac962f4bcbab1343640 internal/cbm/vendored/grammars/objectscript_routine/parser.c+2fde85097c7df0180b7a204eeae97c32a541f1fcc1b44a3837a57f26ac9966fa internal/cbm/vendored/grammars/objectscript_routine/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/objectscript_routine/tree_sitter/alloc.h+31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/grammars/objectscript_routine/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/objectscript_routine/tree_sitter/parser.h+85b458dc150c4d17873dd5e73d01cfa23c797997a09d841884e08378242e929c internal/cbm/vendored/grammars/objectscript_udl/LICENSE+f3a047fba6d238da258c0370878e703504b347aad13add09a021935daa891bd3 internal/cbm/vendored/grammars/objectscript_udl/objectscript_common.h+2003ffb1a07ec30a2f7176c65aae958b804074af8356a81a3d42417a240f2e15 internal/cbm/vendored/grammars/objectscript_udl/parser.c+2e80c4939726948b0ebf8af56103a9c0278a038eeb5be0b769c59d2b4e2d36b1 internal/cbm/vendored/grammars/objectscript_udl/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/objectscript_udl/tree_sitter/alloc.h+31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/grammars/objectscript_udl/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/objectscript_udl/tree_sitter/parser.h+f977a20805dd6e275f14bc090a5f8e638401dad4df366841c1060f12c75b74ae internal/cbm/vendored/grammars/ocaml/LICENSE+e4934793536f53c076b24b16de2f6a48a125c632e6cce58c80c02d6d65f8dbed internal/cbm/vendored/grammars/ocaml/_common_scanner.h+ab85b3756c106d0be3509db9d33eb883ff7dda2b714c7e47ec36a2d807923c0f internal/cbm/vendored/grammars/ocaml/parser.c+e60c3197078dda191119ad786e535835cfda86427d6bebda36bf46ae0956b05a internal/cbm/vendored/grammars/ocaml/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/ocaml/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/ocaml/tree_sitter/array.h+a1f6ef161fbaf48a0e10fca90ef5290a062462b307b3898aa562993853b9f80a internal/cbm/vendored/grammars/ocaml/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/odin/LICENSE+bf6bc6ff36e29e5e611182f79e93ce7e48c04bbb31cf72d7b5bd292a7590e7d3 internal/cbm/vendored/grammars/odin/parser.c+fafd2e286865aacc132e938c1640f51619ec9e7866cd2d8debff39540336c14a internal/cbm/vendored/grammars/odin/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/odin/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/odin/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/odin/tree_sitter/parser.h+2e2fcc500eacb15b76c11fd2229aebf0a5b4c8ed476f068447c6dce778a17ac9 internal/cbm/vendored/grammars/pascal/LICENSE+6db3411bfeff9fea8e64a1436f13b4c3558c52df0c19ea038a6a22fecae1b6eb internal/cbm/vendored/grammars/pascal/parser.c+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/pascal/tree_sitter/parser.h+68a9a526ae357ed5a2f8ca5dabb14131b283554b69639bb04816088d4b1f2fa0 internal/cbm/vendored/grammars/perl/LICENSE+cb08206e89750c1fab700b89fc9876afb5cc689827e514ef49a5569c54635b61 internal/cbm/vendored/grammars/perl/bsearch.h+25c014ab8ce027992a6cfd76ef7b88bf3a41f63fd6ad43f38a553e218a7a9ea8 internal/cbm/vendored/grammars/perl/parser.c+fe4dc0394501b3d6211dcc1e31e9731befae844fcd6db0130e3c16f992d85860 internal/cbm/vendored/grammars/perl/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/perl/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/perl/tree_sitter/array.h+a1f6ef161fbaf48a0e10fca90ef5290a062462b307b3898aa562993853b9f80a internal/cbm/vendored/grammars/perl/tree_sitter/parser.h+9cbc0731f8c9bd52bd3de9644fd887f20cecea2d17634b20769db4940eadb566 internal/cbm/vendored/grammars/perl/tsp_unicode.h+664764fabf40c0b318e06324a5a12379092a2df25b8cbf2415f71bc0bb352346 internal/cbm/vendored/grammars/php/LICENSE+de8eb36bc8f517ab9f3eaf82e3825d7b3e11b62e9471545f4c906100cfce0e07 internal/cbm/vendored/grammars/php/_common_scanner.h+bc796948b625f74e390cfd1254392136c86fafbd2dc0c9d93360ec20bc6b0dfb internal/cbm/vendored/grammars/php/parser.c+cdefc35f0120a291be3b653539390adb04ab7dcdb7e33e9e17e9d549b8760c29 internal/cbm/vendored/grammars/php/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/php/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/php/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/php/tree_sitter/parser.h+01aa3f7bf8fe0c7d06a983422d5ea7e1a71b1363501eaabfdbc6f2bac95aa5f0 internal/cbm/vendored/grammars/pine/LICENSE+07d9b5ef981fd68b0bb3c7ef8758fa58916d5934802cabf532532aca6b1411f3 internal/cbm/vendored/grammars/pine/parser.c+a22529d5ebfdffddd6cd64d46e128889ff0ca9c08eac9326d7dfe33be9120073 internal/cbm/vendored/grammars/pine/scanner.c+253b44a7b4313a7afd0c505c2fc6e7ce4b8e78955ebf4be3ea000532ec060673 internal/cbm/vendored/grammars/pine/tree_sitter/alloc.h+4ff743903dc46f5db6aa54f31c6b4d160a8a9779e5b2ab1ee59ae7ebcd850ea1 internal/cbm/vendored/grammars/pine/tree_sitter/array.h+a3eb18ef034b3f4255b965a26caa276f9cfe13a79573b402f1a12dc5018052aa internal/cbm/vendored/grammars/pine/tree_sitter/parser.h+cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 internal/cbm/vendored/grammars/pkl/LICENSE+2ba57e11ff281cd40cce39859e6bd7c7dd876dc2d809f041b39fbac8a908a70c internal/cbm/vendored/grammars/pkl/parser.c+ed9e42b4f43116692a74a8d04bdc20af1bea18057a7688ff11b2e86a617a68d0 internal/cbm/vendored/grammars/pkl/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/pkl/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/pkl/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/pkl/tree_sitter/parser.h+109ed1ed2db40c798111e05757f5b8576fe14bdb17aa24c7f2515b300c78572c internal/cbm/vendored/grammars/po/LICENSE+35b39cd46f3e2d7ca65534d5b17ddda8e7a466829b28d5988fd776cf1db07182 internal/cbm/vendored/grammars/po/parser.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/po/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/po/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/po/tree_sitter/parser.h+e8d649c1f03766310c675dc46e9733748ca1a9eedbc5196f3247196eddcbc31f internal/cbm/vendored/grammars/pony/LICENSE+1e83917cdc0b678a68d0d36a24e31ce06b15d0329cbcf6ff5a7b5a00b0a32691 internal/cbm/vendored/grammars/pony/parser.c+9bbb7fb8a9f03f291f4656520bd22afc99fd3347439affc4c3dc9cea4ae7f941 internal/cbm/vendored/grammars/pony/scanner.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/pony/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/pony/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/pony/tree_sitter/parser.h+1fca8454c0d77a73f9922a52d39e1f7c339f5da5d03f2766eff66b859fa19477 internal/cbm/vendored/grammars/powershell/LICENSE+a050788086b9d9eda4579f6be7119bfcadb12765b1c2199aeef42afc79c4f50f internal/cbm/vendored/grammars/powershell/parser.c+a2b93528f4e161b1a6e40b4b94390306c667e4af15599771d6940f11eff37be6 internal/cbm/vendored/grammars/powershell/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/powershell/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/powershell/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/powershell/tree_sitter/parser.h+fbce36bb615a015ea545373da62c178fe9e7e3a7b7de656455738e6f671aa652 internal/cbm/vendored/grammars/prisma/LICENSE+187d7d1cd881c3a77391682feaa17ed221d417aeefaaa81070780e7f234f4448 internal/cbm/vendored/grammars/prisma/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/prisma/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/prisma/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/prisma/tree_sitter/parser.h+3297073719030b7261afd78b7267931ccc03a27f7a65ca6fc644316180f71bf6 internal/cbm/vendored/grammars/properties/LICENSE+98e06c3a7b3043d7641ec0b2c28c9f66e54341e343e1f553f994ae5a6f0c0452 internal/cbm/vendored/grammars/properties/parser.c+3c00e7a8ec38662b05cb00858d2959b123b2b5c783eb3dc25c80b7577b4c27ac internal/cbm/vendored/grammars/properties/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/properties/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/properties/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/properties/tree_sitter/parser.h+1f58f9911dc5e3bcb96de28bb28e7b6bb7eb323952d29569c5d7214a152146bb internal/cbm/vendored/grammars/protobuf/LICENSE+0029c486379508543e4822d6c7842df15058fe560377a19a51992eeb527013b6 internal/cbm/vendored/grammars/protobuf/parser.c+c569eeb34b7ed816b3a0a43c4cb8c06b36a6ef1164bc82ebed5047284cd73036 internal/cbm/vendored/grammars/protobuf/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/puppet/LICENSE+3f30def49d50878d0d5b28a279721af0fe3dbc6c82a51e14a4609bd8465339c4 internal/cbm/vendored/grammars/puppet/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/puppet/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/puppet/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/puppet/tree_sitter/parser.h+3ae7f9f8e25ac9a5466114a8593c138c8cab8d34898b57db4fc3f0c3f22eca98 internal/cbm/vendored/grammars/purescript/LICENSE+c6adf243e3c6fe086cef0e2304b8a611b4929ce94387282046494a192bd600c8 internal/cbm/vendored/grammars/purescript/parser.c+f2f9372fe6bab085181d933b6b1b5e1543ec6a1826f56245c4db08967a513cd0 internal/cbm/vendored/grammars/purescript/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/purescript/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/purescript/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/purescript/tree_sitter/parser.h+eb9d38c9e198c2b902954bd4745d4f042e3f7f40ce161a547b3b5d6c144435e6 internal/cbm/vendored/grammars/purescript/unicode.h+d724405ce238a22c0d35769c5a36b386ad5958192efe8bbb304fb2896254575f internal/cbm/vendored/grammars/python/LICENSE+879a2d6bbcbdb8787b2d14998ed4aceb99f7caf017cbe78b38199f234b3d1222 internal/cbm/vendored/grammars/python/parser.c+e16c1f646619d2fb8f8aaf00023b490891630b616551a49887ef69c1fcc01717 internal/cbm/vendored/grammars/python/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/python/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/python/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/python/tree_sitter/parser.h+a8fb3a7df5ba9ef3b6511a1d65ad69869de66828fe2d690b7b65913678739738 internal/cbm/vendored/grammars/qml/LICENSE+da82f082ad20cba807cd4fd543bb66de82f0203b4a249c1da763e0f22defaaa5 internal/cbm/vendored/grammars/qml/parser.c+bfb77d967596144bd1b69b8c418b671ed0885d4fb78ca648c4feb93ff80ef558 internal/cbm/vendored/grammars/qml/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/qml/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/qml/tree_sitter/array.h+a1f6ef161fbaf48a0e10fca90ef5290a062462b307b3898aa562993853b9f80a internal/cbm/vendored/grammars/qml/tree_sitter/parser.h+9866e0d62c7dbbe672ade98649db49258e8d076bd40e433db0e5ee92982ca99d internal/cbm/vendored/grammars/qml/typescript-scanner.h+de2e49529f03d573bc3fa229dc83acfe22c63a5ad1766b289563edfd45b72dea internal/cbm/vendored/grammars/r/LICENSE+830fb35738ae34af5e3d0c3edef70c4dbde5bf78ed6cb6fb4b6b9dc33ffdd052 internal/cbm/vendored/grammars/r/parser.c+beed33f7bc1614111642252bf260c900ba3d067ddc8905ade9aaeb77c17f68ae internal/cbm/vendored/grammars/r/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/r/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/r/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/r/tree_sitter/parser.h+cc35bd4a973bf6067558e88b56d9a369e02c36e240b2b537aef8f751b7808fd7 internal/cbm/vendored/grammars/racket/LICENSE+bdaa99cee35fd4dd2ee74b9414a11a7a14d83395ff9bd721d9ecab391b590008 internal/cbm/vendored/grammars/racket/parser.c+65319c01fcca2fa46f627aefb44f3bc4431bed9837cb799838a3f86b4f275c97 internal/cbm/vendored/grammars/racket/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/racket/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/racket/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/racket/tree_sitter/parser.h+2e0110e07abef7c2548b26ec9d6969775617ca539a0dc8dbeeb14d6452c711d1 internal/cbm/vendored/grammars/regex/LICENSE+1bbb0defd240fcd4ffbba922d9932e307c88db7e7927cd343453a5aa73e3c4ff internal/cbm/vendored/grammars/regex/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/regex/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/regex/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/regex/tree_sitter/parser.h+9cd353e181337293bdfaffdeb0dd784aa11dd28947fb5877d6e46fe8cd0efdfc internal/cbm/vendored/grammars/regex/tree_sitter/runtime.h+413ec4c3842f95bcaf662aba7d646b22baf044aa6ac5efa6531b94d4ee00248b internal/cbm/vendored/grammars/requirements/LICENSE+01f08917f7343ee4c195cc35097cba94ccaa628b532a4861012f85ac308adb23 internal/cbm/vendored/grammars/requirements/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/requirements/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/requirements/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/requirements/tree_sitter/parser.h+21da9b4e463af4b4501cbd4e0c5886a1f321a740b584002a9c9a5fe7b2d46a8a internal/cbm/vendored/grammars/rescript/LICENSE+d75538517e1024056c206f6d1b10cb4ed83670a5d6fb338dbad7b2bb4269403a internal/cbm/vendored/grammars/rescript/parser.c+4bf614fc0b599bf75414c1512e92c971d4bb04d0334e5f562ff34a0dbd745f8a internal/cbm/vendored/grammars/rescript/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/rescript/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/rescript/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/rescript/tree_sitter/parser.h+c6137844f3f63aa4522dfc1cde8dff4f3314ed594ea954a73e3073dcc9d33b11 internal/cbm/vendored/grammars/ron/LICENSE+39ea6d4446a13bd5d72cf3a7cbb1e3d80569630bb5bc9ad13ee78dcc644bd794 internal/cbm/vendored/grammars/ron/parser.c+2157e46b31eee0596a8b36f92e35e9bcce78038dee18891400be1ff1485f0a36 internal/cbm/vendored/grammars/ron/scanner.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/ron/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/ron/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/ron/tree_sitter/parser.h+5b337e5d1fedbb6275550101f7a1e7b00465409d32a29b308812fca394348500 internal/cbm/vendored/grammars/rst/LICENSE+088501c80fb77fab91aa6707b41e8db8aef4a10e1250ccfc4eef312a7c03bc36 internal/cbm/vendored/grammars/rst/parser.c+170cb2ce48ccd5052e429074d368d35d40de936097bee48b070667035fa40601 internal/cbm/vendored/grammars/rst/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/rst/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/rst/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/rst/tree_sitter/parser.h+5885501143828d5257a8bb4f8ab210b2732275689848685709708aab39c58384 internal/cbm/vendored/grammars/rst/tree_sitter_rst/chars.c+7c0359edcfed8eb917636b6ec5c9bf0af96c06ab5680eb613eafc7ae9663036c internal/cbm/vendored/grammars/rst/tree_sitter_rst/chars.h+f9c415b15e461ca438bdf2fae0904325f29112e7bb2151d3657e38a14f822f94 internal/cbm/vendored/grammars/rst/tree_sitter_rst/parser.c+87bcef2d0f435f13d91548b7d16409efaf654e04b5680cbadadfe2e514b8f41b internal/cbm/vendored/grammars/rst/tree_sitter_rst/parser.h+30ed673d03c187056edddff2c8be2027d7d7e48940a3fb25acc4f95789b27cdb internal/cbm/vendored/grammars/rst/tree_sitter_rst/punctuation_chars.h+52f1e03d13f87879d6c0358eff871e6ef9a46f61a874488e6f8d811ac942ad50 internal/cbm/vendored/grammars/rst/tree_sitter_rst/scanner.c+0c4857d7b9b7300b285a6b5f21e37e7994998638adae2be97f954654ccd6e053 internal/cbm/vendored/grammars/rst/tree_sitter_rst/scanner.h+9c9b32c7d37c132447734015d30cb91123bed1ce723d4dae6d3f3b73d976f3d8 internal/cbm/vendored/grammars/rst/tree_sitter_rst/tokens.h+ee006f02a3d856df282e409be2a86e24a65bb573a98b9c28343771141351bb6b internal/cbm/vendored/grammars/ruby/LICENSE+70d24bd0959756f1d815ebe501aeab860b5ef72a7c89c980e99e45d165db0c30 internal/cbm/vendored/grammars/ruby/parser.c+6011c9159b3dbfa77edeaeda4a1f63b3e89450de313ba51d8808e2d9ad753909 internal/cbm/vendored/grammars/ruby/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/ruby/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/ruby/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/ruby/tree_sitter/parser.h+31d5b6f4243d5c7c6e1c4ebbbb9f6407bd1457a08bcc4f706521710341acba36 internal/cbm/vendored/grammars/rust/LICENSE+a9d9e10031d666308dffeb90bbe85a4cafc2282bb9750a3d08c698f3702d6383 internal/cbm/vendored/grammars/rust/parser.c+0d20b632adb171a7246ccfb61fadc1772ce0010b071d96768a0fdfffec8da119 internal/cbm/vendored/grammars/rust/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/rust/tree_sitter/alloc.h+db7d66e4305e3f37b5d31a3291acc01fed95054474a75b3c7cff72048ef9b797 internal/cbm/vendored/grammars/rust/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/rust/tree_sitter/parser.h+1f95ed26e1f4074074c9c7083e61c0a9e4c3b9f435745044995f3beb4ed28575 internal/cbm/vendored/grammars/scala/LICENSE+1b2a6bf2d3a05aada31d8d5806e0ff8b26d62eb7e1466a45c2dd24c3e385361a internal/cbm/vendored/grammars/scala/parser.c+7736bf5a9d2012f96d6048d303a59410919439f695a068badd89cccf51887351 internal/cbm/vendored/grammars/scala/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/scala/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/scala/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/scala/tree_sitter/parser.h+cc35bd4a973bf6067558e88b56d9a369e02c36e240b2b537aef8f751b7808fd7 internal/cbm/vendored/grammars/scheme/LICENSE+83c8586d1b9e1e0c83127b5482df60561a733a267ddb59498b66bcf30620b5e4 internal/cbm/vendored/grammars/scheme/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/scheme/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/scheme/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/scheme/tree_sitter/parser.h+ad64f38da1571e9042cef6bea8f4232c2761c2f52ae93cbada9ae7aeaeeafa74 internal/cbm/vendored/grammars/scss/LICENSE+1e153993c2643b219dd2d5e36982be70d8df7427f74d7849624f22c1d2a6da40 internal/cbm/vendored/grammars/scss/parser.c+679847c7bfb0f2b52d7072cd41d3dbd737a341b29ea3355ff59cd6b960cb1868 internal/cbm/vendored/grammars/scss/scanner.c+253b44a7b4313a7afd0c505c2fc6e7ce4b8e78955ebf4be3ea000532ec060673 internal/cbm/vendored/grammars/scss/tree_sitter/alloc.h+4ff743903dc46f5db6aa54f31c6b4d160a8a9779e5b2ab1ee59ae7ebcd850ea1 internal/cbm/vendored/grammars/scss/tree_sitter/array.h+5bc67343c2bbda4e515ce1b90db08efe983f1ae1f97bf61d67b282dad5346a04 internal/cbm/vendored/grammars/scss/tree_sitter/parser.h+188fdcca13247f567cddb0d5155c622de1a6cf3f0245e52f0986907b6c2819f5 internal/cbm/vendored/grammars/slang/LICENSE+168e29a968b28fbd22633263c71690cf87ba1f04fc74d7163123d1d5e2a81611 internal/cbm/vendored/grammars/slang/parser.c+7df46ad5ae5a965486b9ddb1f91393152bef8cb46a13e8ef6a8a346f0f37d4f8 internal/cbm/vendored/grammars/slang/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/slang/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/slang/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/slang/tree_sitter/parser.h+9cd353e181337293bdfaffdeb0dd784aa11dd28947fb5877d6e46fe8cd0efdfc internal/cbm/vendored/grammars/slang/tree_sitter/runtime.h+1337ef2684df318a38036aeecfcdd4a041368de0b73c300c709da259bf994246 internal/cbm/vendored/grammars/smali/LICENSE+c24c413739a287fff9904b095b67433b5d96d58785a3bed444b837f7779bc13b internal/cbm/vendored/grammars/smali/parser.c+3c2e6fd28dd769a1cec333753808aab73eaca627fe9b0392241308259e270b2c internal/cbm/vendored/grammars/smali/scanner.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/smali/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/smali/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/smali/tree_sitter/parser.h+c51b88530abf05268b117585ac199b590d160de1d49e763fee745c07518b7c54 internal/cbm/vendored/grammars/smithy/LICENSE+b6e2a4c7702007d9998b786635beede0aa9f2fc667f432eb778a5c8fb3cd21b8 internal/cbm/vendored/grammars/smithy/parser.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/smithy/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/smithy/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/smithy/tree_sitter/parser.h+8844f0cc9b76b9c8a9d0251904eb7536b6bb9976e0ec577e8f27ab96d42523ef internal/cbm/vendored/grammars/solidity/LICENSE+69cea66e2ccc152b81e0e6ef4a0a12b0049ea69408c41b020ca1e60b5957b832 internal/cbm/vendored/grammars/solidity/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/solidity/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/solidity/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/solidity/tree_sitter/parser.h+c3d045abbc0a8dec1b00737c0668f6dbb028d248521b74e79778c726671925ed internal/cbm/vendored/grammars/soql/LICENSE+8e5ba685b254227e14a708dfb0536518a3c5c8dad3cceb4d0607f53a4a7543db internal/cbm/vendored/grammars/soql/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/soql/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/soql/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/soql/tree_sitter/parser.h+c3d045abbc0a8dec1b00737c0668f6dbb028d248521b74e79778c726671925ed internal/cbm/vendored/grammars/sosl/LICENSE+624796e29fe84687a7fd435967e2c59912daf83806b869792e31175619504217 internal/cbm/vendored/grammars/sosl/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/sosl/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/sosl/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/sosl/tree_sitter/parser.h+3b3e4e4252d5d7d1c18e1257005f23242bf0580ad619204fd093c99b8c56748d internal/cbm/vendored/grammars/sql/LICENSE+ccee90722c4d0a13b65c534dede1434107c693e405cebb9044199c66a9be0865 internal/cbm/vendored/grammars/sql/parser.c+11378bf572fa0f3ff7bc4d704e49ecd3543c26b3987c7e6e5cef342afbcabe2f internal/cbm/vendored/grammars/sql/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/sql/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/sql/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/sql/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/squirrel/LICENSE+c1c8dd513f3513b1759b48fcd5b63ff510b3f71ae21adc4aa253edebdd31caae internal/cbm/vendored/grammars/squirrel/parser.c+ca17bdf19d6725d5cbdf927ced9da99b00d41f18538d84d08dbbae06038a375c internal/cbm/vendored/grammars/squirrel/scanner.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/squirrel/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/squirrel/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/squirrel/tree_sitter/parser.h+3297073719030b7261afd78b7267931ccc03a27f7a65ca6fc644316180f71bf6 internal/cbm/vendored/grammars/sshconfig/LICENSE+e9b9f37ba99efd9304abb6eb52156a7cc897503d83429d5365e9a3840e8d4082 internal/cbm/vendored/grammars/sshconfig/parser.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/sshconfig/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/sshconfig/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/sshconfig/tree_sitter/parser.h+099c44248f8cf353123211318680e93465587c005a4b3730ce8cb5334de043d6 internal/cbm/vendored/grammars/starlark/LICENSE+d678513b44ef79374f263200f82bf84f9e0dc2bb543d6a7b7fe48be0dbc74def internal/cbm/vendored/grammars/starlark/parser.c+0fc5fc6b61c965c2ce44687ed86dc744a0948b9aff79a15492d525db503ab0f3 internal/cbm/vendored/grammars/starlark/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/starlark/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/starlark/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/starlark/tree_sitter/parser.h+0eea8dc45e89deeb03c7799bbbc7b4688f365fb274562f4540ecfebdea82e727 internal/cbm/vendored/grammars/svelte/LICENSE+fb3ff8378a773e93a1f02d01e7884aa8ee2b13ef81ca8b9ea3c584cf46bb7629 internal/cbm/vendored/grammars/svelte/parser.c+ca411aed71d35c07eeeb8ecb98dbde0f6475fbb323761801b7c75116461e08c9 internal/cbm/vendored/grammars/svelte/scanner.c+38d0f2356661128c2598660271ee9cd061ab50e7ca42b8275118f005899da47f internal/cbm/vendored/grammars/svelte/tag.h+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/svelte/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/svelte/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/svelte/tree_sitter/parser.h+c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4 internal/cbm/vendored/grammars/sway/LICENSE+8aa810fb90d88b611fba95d46b18167f3fc451144eb5342e528e8b589354a33c internal/cbm/vendored/grammars/sway/parser.c+991af9d2b9523fecf531037925c7b2fff514c28a47f05f07ec9b00f77fa30047 internal/cbm/vendored/grammars/sway/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/sway/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/sway/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/sway/tree_sitter/parser.h+3533cec129bb4bba015c0d61d86dd7c3b7e82110e4d2ff7837a01eff5bad5ccc internal/cbm/vendored/grammars/swift/LICENSE+93e6b39fc5b16ef9d5869862ec8d56380a838355c362481942942d59ca666de2 internal/cbm/vendored/grammars/swift/parser.c+b835c1ded068e902944fe82c3770b9dcf85f67dcaab8fbf772f1606007da7373 internal/cbm/vendored/grammars/swift/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/swift/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/swift/tree_sitter/array.h+a1f6ef161fbaf48a0e10fca90ef5290a062462b307b3898aa562993853b9f80a internal/cbm/vendored/grammars/swift/tree_sitter/parser.h+f4ceaa91e73e623d6b30895a3b644e0e277754a81c8b28655b75d7a9113f1ac4 internal/cbm/vendored/grammars/systemverilog/LICENSE+64700407b92a3ba55fc445009ca187c84dd8959a43260d91b43dd1b519b1dac4 internal/cbm/vendored/grammars/systemverilog/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/systemverilog/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/systemverilog/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/systemverilog/tree_sitter/parser.h+4d6033889c2f0e054589c67aa638e59e609b029c62b993c9659ebba19abfde5c internal/cbm/vendored/grammars/tablegen/LICENSE+97551497dfb24aae347e8590c6fd26236434d9458ab1097c201e2e9f240c17ad internal/cbm/vendored/grammars/tablegen/parser.c+b7d8d788dcc3e7509f35502ab3bb6f5c54744e6441eba6407bdca48371517f65 internal/cbm/vendored/grammars/tablegen/scanner.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/tablegen/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/tablegen/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/tablegen/tree_sitter/parser.h+e3578fe6a7e9592bd4d39fb52d2be62c07e5f8bdca2ca66b3e22f553ec8351fb internal/cbm/vendored/grammars/tcl/LICENSE+2c55860b00bd651a7cd6c9892191a8125567df8318b3cc1766dc9ff347ae5aea internal/cbm/vendored/grammars/tcl/parser.c+c8684aca686a7f096a662633c51833e360ca0c56a8e9502719b2f73b0bd41b71 internal/cbm/vendored/grammars/tcl/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/tcl/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/tcl/tree_sitter/array.h+fdc6c206253cee98e7ed2d32cf27c6497ec4de47aef2f630796f3d249bb5e447 internal/cbm/vendored/grammars/tcl/tree_sitter/parser.h+b2ddc8d974b4a74abebd8a4ac19b8fbfa3f4d37ec5b88f748cdfda3c76a22797 internal/cbm/vendored/grammars/teal/LICENSE+16b605f36ec0dcfdef450b4bece69266fafad6126e0cbd8cc66da2fa5df7fe98 internal/cbm/vendored/grammars/teal/parser.c+e5195d852b9b5d569a53e83e0afe4fdc746c08f661e287f63e00c62e23f05b72 internal/cbm/vendored/grammars/teal/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/teal/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/teal/tree_sitter/array.h+fdc6c206253cee98e7ed2d32cf27c6497ec4de47aef2f630796f3d249bb5e447 internal/cbm/vendored/grammars/teal/tree_sitter/parser.h+fb8a4a7edd1e655b1ecf15dd5324fd9c073bbbf07e50c064566c693d854a0f76 internal/cbm/vendored/grammars/templ/LICENSE+02e16d32ea15c2446dd2abecf868ef0b1d4445452e1221d8398171e33bed325f internal/cbm/vendored/grammars/templ/parser.c+a66b60d32dd3e2856848a560cf7e9b88b32784bce82dc8a101433a9f1fb6ebbe internal/cbm/vendored/grammars/templ/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/templ/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/templ/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/templ/tree_sitter/parser.h+f0a0f84bedde3f160f9db0337715a534ca8f1fb5f19726d743dadfde44bb08c8 internal/cbm/vendored/grammars/thrift/LICENSE+b1014cb78e3d88f7f560ce2862985ba115c62f3bf3f8a96b30591831654f01bd internal/cbm/vendored/grammars/thrift/parser.c+b052d4e482289de2d085b61d3ae016edf931ffe63deef7f9dc4fed5a42af2cee internal/cbm/vendored/grammars/thrift/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/thrift/tree_sitter/array.h+21e97816f542d2100ea1e0baa749642ca52801a5d6e4af5ee51eb21bfa8e6509 internal/cbm/vendored/grammars/thrift/tree_sitter/parser.h+bb9ed59c3ddf6631a6138e4656fbcf7fb225b1a3260760e729d6e58a52c6b15a internal/cbm/vendored/grammars/tlaplus/LICENSE+b17dd51f585e71cb15f5e73db111e26220166eba9cfd1be40a30d9bc382d84a8 internal/cbm/vendored/grammars/tlaplus/parser.c+66e55aeeb49d0282e5fa0363c5cdde0f3cf28ae647a53ff5357deaeaf68698e4 internal/cbm/vendored/grammars/tlaplus/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/tlaplus/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/tlaplus/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/tlaplus/tree_sitter/parser.h+b727eee929bee836e8102cecf749a795b199f291b58c885bcd81cae727ac5a46 internal/cbm/vendored/grammars/toml/LICENSE+1210d0b755e184d11a92f2b312980b2bfcdb5d215b5bb87129607651863de350 internal/cbm/vendored/grammars/toml/parser.c+32cf77802e4e46ed57697a6994f60f1bda332302d79be2a289c38b0c911e824e internal/cbm/vendored/grammars/toml/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/toml/tree_sitter/alloc.h+194347784d78c4085d6712a7c2d543974e31f911b5b32ee15444931e196fbfbb internal/cbm/vendored/grammars/toml/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/toml/tree_sitter/parser.h+49bf33cf78ef5897e4e161ce1517df7de1ae5042a65b6bcfd44401e0fc606559 internal/cbm/vendored/grammars/tsx/LICENSE+da66ef2bd14a3f7ea743e25ba068c6c9aae2c3509db200ff80c4a0e6116e564c internal/cbm/vendored/grammars/tsx/_common_scanner.h+1902cb53fa7ff5179df89b2eea863165e84c8cc866226419dc26921d8c055885 internal/cbm/vendored/grammars/tsx/parser.c+7a2fe1ae9928ef0ac74dae3a9d02c85b6be31f08d65f0e9697d215b62c991ec2 internal/cbm/vendored/grammars/tsx/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/tsx/tree_sitter/alloc.h+4ff743903dc46f5db6aa54f31c6b4d160a8a9779e5b2ab1ee59ae7ebcd850ea1 internal/cbm/vendored/grammars/tsx/tree_sitter/array.h+a1f6ef161fbaf48a0e10fca90ef5290a062462b307b3898aa562993853b9f80a internal/cbm/vendored/grammars/tsx/tree_sitter/parser.h+49bf33cf78ef5897e4e161ce1517df7de1ae5042a65b6bcfd44401e0fc606559 internal/cbm/vendored/grammars/typescript/LICENSE+da66ef2bd14a3f7ea743e25ba068c6c9aae2c3509db200ff80c4a0e6116e564c internal/cbm/vendored/grammars/typescript/_common_scanner.h+74fe453edd70f4eae9af0a1050cbd7943d8971d59165b6aaebbaa0a0b716d1aa internal/cbm/vendored/grammars/typescript/parser.c+fea1cc84d0bbc053835a10a71db26af5f199464ae479d013ce72cc5a942a08f8 internal/cbm/vendored/grammars/typescript/scanner.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/typescript/tree_sitter/alloc.h+4ff743903dc46f5db6aa54f31c6b4d160a8a9779e5b2ab1ee59ae7ebcd850ea1 internal/cbm/vendored/grammars/typescript/tree_sitter/array.h+a1f6ef161fbaf48a0e10fca90ef5290a062462b307b3898aa562993853b9f80a internal/cbm/vendored/grammars/typescript/tree_sitter/parser.h+0d129fe54977b282fa928da9bcf1f609d3388b54862361c9292d83605f71bd4b internal/cbm/vendored/grammars/typst/LICENSE+eeb1ce8085d748ea8ec44b337b179a676dfab4549593b834e9c510362e795b64 internal/cbm/vendored/grammars/typst/parser.c+697d1189b63a89b5f80c687a360fb5c6402754644064886d1000835ed431ca31 internal/cbm/vendored/grammars/typst/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/typst/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/typst/tree_sitter/array.h+2db740ea1be6b71014d2be1385491f01bf2d15b607e61c5b30b4128535efe68a internal/cbm/vendored/grammars/typst/tree_sitter/parser.h+6d1a6e017b78433535460ceb3e386d92d8c5dca6e85e6919d5810f1f9aa665a1 internal/cbm/vendored/grammars/typst/unicode.h+8d2ff8d1e308828099436c43dc8bfbb8b6f368ad2a012ab9802a80ca22b03b53 internal/cbm/vendored/grammars/verilog/LICENSE+bb0f5fe2423ac18a4ab15d8201a2cf155c874b52f3a3022a16e2aa58bb92a4d9 internal/cbm/vendored/grammars/verilog/parser.c+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/verilog/tree_sitter/alloc.h+4ff743903dc46f5db6aa54f31c6b4d160a8a9779e5b2ab1ee59ae7ebcd850ea1 internal/cbm/vendored/grammars/verilog/tree_sitter/array.h+df898ca6d3eb880b9fdf7d3179363d7657abcd4b0a0565d8fd6b47215d8cc149 internal/cbm/vendored/grammars/verilog/tree_sitter/parser.h+a9323218abe9aabd3429b76634470b40c3be012600e1f96bd16ca254724fa954 internal/cbm/vendored/grammars/vhdl/LICENSE+35b86315cac1e7c8caf157c6adf12d25bb58fba2fd4e766b43613046fcb67893 internal/cbm/vendored/grammars/vhdl/TokenTree.h+b58ab34db45a9b0f097f5dd549e375fd3e2e9355d0ef20e27ff8cbecc76ec247 internal/cbm/vendored/grammars/vhdl/TokenTree.inc+b0eacaa21138fa29f06d74946d66017e79684f27fee91b0288745b33d2a03839 internal/cbm/vendored/grammars/vhdl/TokenType.h+cefde62d6d773164c8a6108420d35327d5b8fac695b6b35bbd5741ff370aa44f internal/cbm/vendored/grammars/vhdl/TokenType.inc+d67c7d65af0c5a7209a535255d5de74e92fc994e445a8dda36bc5873ffcfad2e internal/cbm/vendored/grammars/vhdl/debug_macros.h+bab4235e812f15e5165536dd9c271248287fcc3a8fbd22c6faa8e4121cda5482 internal/cbm/vendored/grammars/vhdl/parser.c+9c77212bea6fe941503739ac12d2751e6b59982914e39268efe55307fa3cdddb internal/cbm/vendored/grammars/vhdl/scanner.c+1b61902d6ebba726800ca82b39df00e8522b3db804027879df4f54d294840fff internal/cbm/vendored/grammars/vhdl/token_tree_match.inc+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/vhdl/tree_sitter/alloc.h+31e60a1bff6f715afacce03b5b70efe42b58371b4f9595dd4af52a577ff9608c internal/cbm/vendored/grammars/vhdl/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/vhdl/tree_sitter/parser.h+14eaaaa5c0cdb0eb86e85c55643c4cfa04593dbfbaef6a20f35337667b7278d7 internal/cbm/vendored/grammars/vim/LICENSE+c191ffc9ec9f457783b3ec601fb6f34019a415739f7f7132f40c26eb1afb77c7 internal/cbm/vendored/grammars/vim/keywords.h+003038d0554616b0448164289d57449067c09da48c5f278bf4f8bd794caa6327 internal/cbm/vendored/grammars/vim/parser.c+07e631182cbe9c9655c7b18c22ab44ceb51e71a8ec21d1d903f34370b3457619 internal/cbm/vendored/grammars/vim/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/vim/tree_sitter/alloc.h+db7d66e4305e3f37b5d31a3291acc01fed95054474a75b3c7cff72048ef9b797 internal/cbm/vendored/grammars/vim/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/vim/tree_sitter/parser.h+91ebb180e4e2e34628c45e405584d0faac6863660b69e8139da96290e58c14dd internal/cbm/vendored/grammars/vue/LICENSE+8d118ff4a01b4284bcfbd01084c10aaeea3d7866dd5f1ae8c96ef0a4c3e6494d internal/cbm/vendored/grammars/vue/parser.c+8efe15493f49cd912b67e25bd0f34e6008644e0329479e5265b282cad92178c5 internal/cbm/vendored/grammars/vue/scanner.c+b639821160ac0e1a70d1dc2fe206380da945bd65be7a010ffdb90694a0fef2b8 internal/cbm/vendored/grammars/vue/tag.h+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/vue/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/vue/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/vue/tree_sitter/parser.h+d1b7f7ca8ec73d915cec4aa64d9e8b7f2d89b874225d4532e00d9c36c98528fe internal/cbm/vendored/grammars/wgsl/LICENSE+85fd897fc6aa72ec46d648043335794fd272de724fee31dca460280b5e9fc4ba internal/cbm/vendored/grammars/wgsl/parser.c+765103b03c89069894423d760a305bdccb70638f4cfd39ec25519cd71d9acea0 internal/cbm/vendored/grammars/wgsl/scanner.c+df898ca6d3eb880b9fdf7d3179363d7657abcd4b0a0565d8fd6b47215d8cc149 internal/cbm/vendored/grammars/wgsl/tree_sitter/parser.h+3b26cd02b9d9bf324bce59edd88c02cb93fa9a908528b805264db8cde53295e6 internal/cbm/vendored/grammars/wit/LICENSE+d2c4cab0df0ba3cc692ae0731de4c644ad41114fcfd5b5a7a8ae669df39f8434 internal/cbm/vendored/grammars/wit/parser.c+9749b186b3b7620995d9a9b747d34c39949fc497c20d7b79391799014bad9470 internal/cbm/vendored/grammars/wit/scanner.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/wit/tree_sitter/alloc.h+db7d66e4305e3f37b5d31a3291acc01fed95054474a75b3c7cff72048ef9b797 internal/cbm/vendored/grammars/wit/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/wit/tree_sitter/parser.h+1f58f9911dc5e3bcb96de28bb28e7b6bb7eb323952d29569c5d7214a152146bb internal/cbm/vendored/grammars/wolfram/LICENSE+65c40faeea40dcd6463f05957b1c7b0cec5ea9fd5985e4698393cdb07fc4d4fa internal/cbm/vendored/grammars/wolfram/parser.c+cf420e6e072518b529008c894afe49f115c2019772ecb2846df4e2ca5aa82c31 internal/cbm/vendored/grammars/wolfram/scanner.c+ab104936984904469572a4e868149f7a22fb2929347f837ae6a1f9b790f1b173 internal/cbm/vendored/grammars/wolfram/tree_sitter/parser.h+3297073719030b7261afd78b7267931ccc03a27f7a65ca6fc644316180f71bf6 internal/cbm/vendored/grammars/xml/LICENSE+e00f74ae7edcfc5e0cf9dc551a41a02e88a86dad9d6d13820e292bde794cdd94 internal/cbm/vendored/grammars/xml/parser.c+0cfc21f8bd3ea4711082a3f8f0950cd9802d3c45e32f294c377260c0ec018a64 internal/cbm/vendored/grammars/xml/scanner.c+ce5082af60b1808035a43c3df129df9b811c9c69949fdb664a351f7aae340409 internal/cbm/vendored/grammars/xml/scanner_common.h+b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea internal/cbm/vendored/grammars/xml/tree_sitter/alloc.h+5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94 internal/cbm/vendored/grammars/xml/tree_sitter/array.h+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/grammars/xml/tree_sitter/parser.h+2d181298822a124f6d106118dcc69c8d4d26ac668559be29682c452e712b0947 internal/cbm/vendored/grammars/yaml/LICENSE+b0f4488b00f7c2f5564086a0723eaed408fb61f82ffcad26287bb8dde67ad3e0 internal/cbm/vendored/grammars/yaml/parser.c+7e262b332e4ce356ae04de35abe5b3eb9af0c80132884e04887fb902aa544ad7 internal/cbm/vendored/grammars/yaml/scanner.c+91e56c3f3ae6fad1803b739ce4eb4568a782a9aec710f733db2f3e38d407a4d5 internal/cbm/vendored/grammars/yaml/schema.core.c+3a18e4406aa8cdaea2806483e11c50e1a392fd72cf8f54ab7f189b3728836949 internal/cbm/vendored/grammars/yaml/schema.json.c+4f7ca12361e848214beceaa95ae615048317039ea4736c6eec956e3e8da4694c internal/cbm/vendored/grammars/yaml/schema.legacy.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/yaml/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/yaml/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/yaml/tree_sitter/parser.h+0eea8dc45e89deeb03c7799bbbc7b4688f365fb274562f4540ecfebdea82e727 internal/cbm/vendored/grammars/zig/LICENSE+f43a46ac057d6d4cd54d54336974d5915493559392bebb1db49ebf1b4a39ed23 internal/cbm/vendored/grammars/zig/parser.c+115a75d000bef9c70c4de7dfbb7f2a80b90cbb14ba265056dc7abb1ef3b9b6db internal/cbm/vendored/grammars/zig/tree_sitter/alloc.h+02d139d44303b0b0b85a899839dbc1346c478e7318d1f2971fad2b38fd57cb73 internal/cbm/vendored/grammars/zig/tree_sitter/array.h+c4b9482069f61a2a26a590181baa34f08eb6dcc57a138def578e6f9720c35ea5 internal/cbm/vendored/grammars/zig/tree_sitter/parser.h+49bf33cf78ef5897e4e161ce1517df7de1ae5042a65b6bcfd44401e0fc606559 internal/cbm/vendored/grammars/zsh/LICENSE+c7daeb5262d4ab1ba771881493b52e5d6235f6a74f6e25c1bc65bdc5b5898f88 internal/cbm/vendored/grammars/zsh/parser.c+22db197dc16b8d91dc28504be81d099479fda057ed4eab3358c39991d0de6243 internal/cbm/vendored/grammars/zsh/scanner.c+83a7aebb8067b898fa0975e4c627148ec2407617865b42edc91537f6bf651591 internal/cbm/vendored/grammars/zsh/tree_sitter/parser.h+8b58c446121a109ccf32edc094bba3010a3d85e4ee3702950db55e4d3e87736c internal/cbm/vendored/lz4/LICENSE+b679f60439152d7f7b1ecd1efc4ab8422a996a1d07a524b71657b1f90ea1c2e2 internal/cbm/vendored/lz4/lz4.c+26b82efc53d1570f3b54eef02e9c4764c1ad374ff03cac04e2ced5ea4d4c552f internal/cbm/vendored/lz4/lz4.h+45e2e3c7ef0a7b62820b909452d0bd06f73b76e01281e69601428bcd3a8ba13b internal/cbm/vendored/lz4/lz4hc.c+e43824e8a9ba16f54100c4ccbccfa5782a858ca9ab83c48aac303fea3e76e21e internal/cbm/vendored/lz4/lz4hc.h+e10e0877c3b49180e55eaef544b796570841b3265544ab069f7bc5687b7ec584 internal/cbm/vendored/simplecpp/LICENSE+37d6c64629f806c8136692742232d189532ffd9d1f9dd92cf434c2081d7e9e6a internal/cbm/vendored/simplecpp/simplecpp.cpp+d5b27a5d618b8f917e8bb427af136d8f7a02f9638106101e50bbba9ba084e56f internal/cbm/vendored/simplecpp/simplecpp.h+c5cfb43042b6b72045f4ba997834d0a7786d2793d91680868b5815b39f14fc78 internal/cbm/vendored/ts_runtime/LICENSE+0e60780e057e581a9df989fbb2c7d9c9ffe1ccbcaaa15904e5d0af4540dbbb70 internal/cbm/vendored/ts_runtime/include/tree_sitter/api.h+c7d15b9015568f439af4adf28ead9e2bd14901221819276727c11227a29576da internal/cbm/vendored/ts_runtime/src/alloc.c+2ad7cc5391be8043ffdcc111b9b21b7767f592790fc8389acb6fcee7fd1acb61 internal/cbm/vendored/ts_runtime/src/alloc.h+8d09903d836bd4238242e5d3b7e89d560f61a0ddb7dc297677bd190436770d8e internal/cbm/vendored/ts_runtime/src/array.h+bbc630cb913ac64274ce4412bc9d504174220323993f306ded74abe502867e74 internal/cbm/vendored/ts_runtime/src/atomic.h+0e8d1a21e0d60981e762989108231df6610d95591892f631c6c78a9ef831a2ab internal/cbm/vendored/ts_runtime/src/error_costs.h+6fcee7d2663ac67d88b9e79a03ff4854dde1e8d30d3c985d945bad8017532c52 internal/cbm/vendored/ts_runtime/src/get_changed_ranges.c+f394bd0b6fce006be460fd16cbea3cc96e248c810a4d97e8830463c29c85e4a5 internal/cbm/vendored/ts_runtime/src/get_changed_ranges.h+e1982b9795b9c52b5ab564d8b9876189d65a97ca02f78351e1740b0985992fd2 internal/cbm/vendored/ts_runtime/src/host.h+785c8271fac8c975f3bc605e98e455da439000c1b016354700719155903709f2 internal/cbm/vendored/ts_runtime/src/language.c+56e32fb53672609be6e8bfa7e6d0f92ef463fd53d2be910d169a07ee5f03df1b internal/cbm/vendored/ts_runtime/src/language.h+7fc186fb4bf50233059e8be9ca68efe95e66d34ced4b8a8f38f14497352faeb1 internal/cbm/vendored/ts_runtime/src/length.h+4c740aa267fce15f3ff10911656276113898c7b53fc1124ff9d028a1ff40df55 internal/cbm/vendored/ts_runtime/src/lexer.c+7d76308f7a2d3246a3e28fb27698be928f848130d1bfacc39f9f623127671b74 internal/cbm/vendored/ts_runtime/src/lexer.h+4e28f87edb86e5134d36ff7ba7e09a964ba9966a4b620c2735e3572b53c157d3 internal/cbm/vendored/ts_runtime/src/lib.c+356417378bc34c5fe8a96f591467aeaef4a224667aee72593f182d960c6d4393 internal/cbm/vendored/ts_runtime/src/node.c+27365d26edffc65a70537e2885d5d2e2ef905eee0e9101e6da2fd4477de9cb39 internal/cbm/vendored/ts_runtime/src/parser.c+180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2 internal/cbm/vendored/ts_runtime/src/parser.h+04a101f16f40a651814c0f307fadf3f351d0f24013fa6d8b89c85bf1c6a5e717 internal/cbm/vendored/ts_runtime/src/point.c+0929027be2ff54627be560f3bafc1af59e81ac6d5a8d5864455601a0dbee50ff internal/cbm/vendored/ts_runtime/src/point.h+999c2e28ba10a7c4f054de7c830b0558a431d0a4a87c2ac1439a65f4f67f157c internal/cbm/vendored/ts_runtime/src/portable/endian.h+3daa70dfa654c8b2fe82eb75f4675dcd838f1fd546ca04c96abcf2aa6f89ecf4 internal/cbm/vendored/ts_runtime/src/query.c+8f40396e431d7ff558694ca248eed1332b6cf6f7e6255f06cddfde78020bd308 internal/cbm/vendored/ts_runtime/src/reduce_action.h+10be747ea4c733ca181dc43d55d155ac8e5b8caa247079621cca0ce633347bfb internal/cbm/vendored/ts_runtime/src/reusable_node.h+477e5d5a30937d21adb16ce1a8edde5d49e809a23c0c7b26ef1ef9a78169557a internal/cbm/vendored/ts_runtime/src/stack.c+13a2fb028036cf889fa92d55c3d7c0b57ba368a274f20a1961e695207cf3b91c internal/cbm/vendored/ts_runtime/src/stack.h+f9bc00ed98c2bf1d81a6954f9efee667312a3613d8efa506707341470125975c internal/cbm/vendored/ts_runtime/src/subtree.c+93a2acaac1dc7cf9dcf1ad19eae0324d1f6469c9bf142d1c240f796234430d1b internal/cbm/vendored/ts_runtime/src/subtree.h+06f7fece283fd9eb0eed3209b159ba82dba2daf3b7fbf5959bd21c527d8aac55 internal/cbm/vendored/ts_runtime/src/tree.c+60591fb35ca078a8bb323004ece0377ac4f4c6cdbd3c4473af6e2b97186e024b internal/cbm/vendored/ts_runtime/src/tree.h+8d94832d6d68784252b2ff4c8abf9c37dd1672d2af9c4ab5588f342ed44b106e internal/cbm/vendored/ts_runtime/src/tree_cursor.c+3e8d9671ab1397bcaeb3e0cbf153a61a99e214782b43c09e5cde5a01e8283a1a internal/cbm/vendored/ts_runtime/src/tree_cursor.h+ac1ec4b7ba388a9d8708feeb6c5c766b2927cecfd6db644b939772e1dc086526 internal/cbm/vendored/ts_runtime/src/ts_assert.h+6cf0ec5a54e72644e506cca20b854dc7c49249cb1cff0d806635a10c8efba340 internal/cbm/vendored/ts_runtime/src/unicode.h+a87e9710c9cad7b08a945f4fb8b9d4629189897cc535f8ac927640c210a94b69 internal/cbm/vendored/ts_runtime/src/unicode/ptypes.h+2d79c0903d9e73e247b948bc0a12b6a785257ca0273bddab56fb59561f8d7391 internal/cbm/vendored/ts_runtime/src/unicode/umachine.h+a87e9710c9cad7b08a945f4fb8b9d4629189897cc535f8ac927640c210a94b69 internal/cbm/vendored/ts_runtime/src/unicode/urename.h+a87e9710c9cad7b08a945f4fb8b9d4629189897cc535f8ac927640c210a94b69 internal/cbm/vendored/ts_runtime/src/unicode/utf.h+c370d9069f37fad2b53981c06dc648bbc21923db1655517a31bb237df4fba041 internal/cbm/vendored/ts_runtime/src/unicode/utf16.h+39651224b2ca2452359c7f3339f3cc0a841fe7db64f8a00c9c5ec19c0389645c internal/cbm/vendored/ts_runtime/src/unicode/utf8.h+cb7322ff2ca3b7e1c46a23ce383f909993dc2f5f8b20356ab073f45db10293f7 internal/cbm/vendored/ts_runtime/src/wasm_store.c+4f70d0500b0775e5d862a8e7d191b3853d73378c65e020e01767838a18debe0e internal/cbm/vendored/ts_runtime/src/wasm_store.h+2ef609c58a83269273396bd1176fc47eeb3fa5bd705b7c7fc2abe2d672740f65 internal/cbm/vendored/verstable/LICENSE+f1db172f4755365af79b1f7ad261669846a8331d273619e39ae4eff50e53d762 internal/cbm/vendored/verstable/verstable.h+6a90b88421a0d9b090e121daa11b3c6d55eed5eeb3281a2fcc454d6a28b5547c internal/cbm/vendored/wyhash/LICENSE+a86b7735823b0408a4f3b922be86d4d25b6f4ab0dab32e03fb77246ca439dcf2 internal/cbm/vendored/wyhash/wyhash.h+7055266497633c9025b777c78eb7235af13922117480ed5c674677adc381c9d8 internal/cbm/vendored/zstd/LICENSE+208e110a1f052d007242d4eef6ed20a03ab1dc6e13eb2c4ff8d158112120ba8e internal/cbm/vendored/zstd/zstd.c+9b4bc8245565c98ccfc61c07749928b57e7c0f6fddb0530c4f6aa1971893d88b internal/cbm/vendored/zstd/zstd.h+66a8c3f71d12ea6e797e4f622f31f3f8f81c41b36f48cad4f5de7d8bfb6aac0a internal/cbm/vendored/zstd/zstd_errors.h+82ade5d7d9b029044b5fbbc326207fc47c2d44ee4dd71e8a559c36d728217de9 vendored/mimalloc/LICENSEdd4f25cae53209d45d73f8e6a2b9c219e8fc7434d97f20eba9af1a8b850030fd vendored/mimalloc/include/mimalloc-new-delete.h21fcf61c4443341ac6bf6ea528af31dc7267e8e3456fc64bfd07704503032175 vendored/mimalloc/include/mimalloc-override.h5260df227ea1612b8678a06b063cc8f48e739b551554541cdeb4d430a7e257b3 vendored/mimalloc/include/mimalloc-stats.h@@ -29,20 +1004,32 @@ d3614a59f2407a32e75b051deb1aff31b233f587d325dcc5420ba508551b687e vendored/mimalce14eb6dfd55f241095b55f70983931a2d92f7a6a622a9b360cdd70ab3b53208 vendored/mimalloc/src/prim/osx/alloc-override-zone.c247a9952465eb105be03a9962e922b085ce5d52034775551a61cd8594275be73 vendored/mimalloc/src/prim/osx/prim.ccc771788e5ba591efb681829a8724f8662a1f50f3db39cf5ebe7738b8ed57e44 vendored/mimalloc/src/prim/prim.c+792531421c247fca0766ff7630057ec491173578ca4d1919ae34f05eb289ccf4 vendored/mimalloc/src/prim/readme.mdc1ae32eaac7ccf18c10058cca99723892f8bd027318590151f5011c929c7e3be vendored/mimalloc/src/prim/unix/prim.cbee9c655a17e1e93bf4908e0a902fd3b566628447b1446fcbfa92bca2e76ca15 vendored/mimalloc/src/prim/wasi/prim.c+f70e61a1f2fe63da2f51c581895cf4a0918a9bffb0cf8600171f297141446962 vendored/mimalloc/src/prim/windows/etw-mimalloc.wprp4f3110ef2054c95cb275be96cb279224d3d46a728c5117bd1435425f382de778 vendored/mimalloc/src/prim/windows/etw.h+445e6a70f9728fcc76a5ba52079336064d5e2257c2969023f1c64bf943776f54 vendored/mimalloc/src/prim/windows/etw.man5cde60fcef94cd79ab816030be00f8c1bdf18fab343563508c681ec6e762d1f1 vendored/mimalloc/src/prim/windows/prim.c+1bcb43eef7fcddf6d8f18c6d5ee9bd350090ed183a1009d4f1c9b4d81a205bb9 vendored/mimalloc/src/prim/windows/readme.mda96a1acc75fd6595811b28420cf0495b87fac98c4dbc73aa0d742b6824f607c8 vendored/mimalloc/src/random.c4059be2a6676693be3433f5aedc711f56301772e65f3573654c236d6d1cfd074 vendored/mimalloc/src/static.c16825bbc252de422982b5728df7eda181d952824f5e3ce958c7fc85feae64b8e vendored/mimalloc/src/stats.c7f76bcace4b0578f2063477752138adabd99f7b10a276998e296a312c47a7cfe vendored/mimalloc/src/theap.c49be69a4b674e09690a63870830f3ffb05698ed4210949ef5add11957a08325b vendored/mimalloc/src/threadlocal.c+cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 vendored/nomic/LICENSE+893a74d9e3f0a74358344edc999e165739df343b36297967f3fd9cd462022f39 vendored/nomic/NOTICEdab3009c0d76b0c5e05ad8abc7c9f8f6effca547fea3c0394be96418a85c1081 vendored/nomic/code_tokens.h+c928f5e2f9dd85f2294a50a05dd9f2f8bc95192727579aa16b062ff8ef301d25 vendored/nomic/code_tokens.txt+c76bba4c5032323ded6202053af5afdbbac12f6d920c691b3b3b4cd708f99e83 vendored/nomic/code_vectors.bin494d329d06e33904e6264b1f9d1cc82de2c6bb212f8d78ba281b7e1eb1179b61 vendored/nomic/code_vectors.h+a4dafde0b9c88d9d4f5c29416f4330d60cd24ee43bcc51babfe863741be88221 vendored/nomic/code_vectors_blob.S+49e5417011e9720fc8a5fa2a400c1541535195788c59ab33888ade39b2a3f9f0 vendored/sqlite3/LICENSE.md+6bcc01e66a9cf52e522e80ba21a30707fabc8568142d7c09abfba7dfdded8ae2 vendored/sqlite3/PATCHES.md190d82e7899c6cf74260f122c4a737f77c68e98e8d516750df8d56e7fc00ad57 vendored/sqlite3/sqlite3.c19585c8b5230e9d4f223bf31b709ece7b6a0bb3faf00d8310625d8e58cda1b1d vendored/sqlite3/sqlite3.hea81fb7bd05882e0e0b92c4d60f677b205f7f1fbf085f218b12f0b5b3f0b9e48 vendored/sqlite3/sqlite3ext.h+6a50ab50d856b30c965cf2dd899e577ec108c938242fd3a2e7a7a25eed996200 vendored/tre/LICENSE7efd127c0fc4fe26a07684345cce9287762346abeab665e2fe72711c6fc118bd vendored/tre/regcomp.ceab23b8e79ee90f78e8495de64519afb61b627e062804fd4a622784e052a85fa vendored/tre/regerror.c26b0f550d491335cdaa3fecfe49213d68466befdf648ed281ccdaa631ea6d4f9 vendored/tre/regex.h@@ -69,7 +1056,9 @@ aabe11f1b7c6c627dc9cfb62cfb9565ac9ebdf2c51c2d55c5320af5db76c5e3b vendored/tre/t90f76dce41eade7e28c3477d8b45acb8d2ccbc6d4aaba0bb93f0d5ec5b160820 vendored/tre/tre_all.c9632e5eeb20e3d328f8def0efb2e8230f5b5cb7d9f2e5680ad89caf065f8b3a6 vendored/tre/xmalloc.c22aee25e6892e97719ec4a5fad91345cd2145722ebbd3ec31397aff68108e3e6 vendored/tre/xmalloc.h+6ffedbc0f7878612d2b23589f1ff2ab15633e1df7963a5d9fc750ec5500c7e7a vendored/xxhash/LICENSE5c3591fe6e6c86a619eb26760e9520e37a6fd5152882ab5ad93f912e2a855966 vendored/xxhash/xxhash.c86d0d813745821bbccf0be6d67356846f138e5c20164c52c24fade1419afdf7d vendored/xxhash/xxhash.h+45e384d3d52c73cba3a64d6e6c25d47cd738cd8a55c30629e3201046eda62947 vendored/yyjson/LICENSE1da0205abb1a27c27db397b7f8a475abc0af58963af9a88fc807a6c4fa7a8d51 vendored/yyjson/yyjson.cb2bd3aec324a0d6bc67196f647c966870e783c2e3944684f10db26b2c04b773f vendored/yyjson/yyjson.hdiff --git a/src/cli/cli.c b/src/cli/cli.cindex 3e8d02bee..986abe452 100644--- a/src/cli/cli.c+++ b/src/cli/cli.c@@ -25,6 +25,7 @@#include "cli/integration_assets.h"#include "mcp/mcp.h" // cbm_mcp_tool_input_schema — CLI flag parser + per-tool --help#include "mcp/index_supervisor.h"+#include "ui/asset_pack.h"/* CLI buffer size constants. */enum {@@ -45,6 +46,7 @@ enum {CLI_OK = 0,CLI_TRUE = 1,CLI_ACTIVATION_PARTIAL = 2,+ CLI_ACTIVATION_RUNTIME_ROLLED_BACK = 3,CLI_ELEM_SIZE = 1, /* fread/fwrite element size */CLI_IDX_1 = 1, /* array index 1 */CLI_IDX_2 = 2, /* array index 2 */@@ -167,6 +169,10 @@ static const char CLI_ACTIVATION_MUTATION_FAILED_MESSAGE[] ="error: activation failed while CBM sessions were stopped; filesystem ""changes that completed before the failure may remain. Review the errors ""above and restart your coding-agent sessions before retrying.";+static const char CLI_ACTIVATION_RUNTIME_ROLLED_BACK_MESSAGE[] =+ "error: activation stopped after a configuration or cleanup failure; the previous "+ "executable and runtime assets were restored. Configuration changes that completed may "+ "remain; resolve the errors above before retrying.";typedef struct {cbm_daemon_ipc_endpoint_t *endpoint;@@ -247,8 +253,9 @@ int cbm_cli_activation_guard_with_ops(const cbm_cli_activation_ops_t *ops,int rc = mutation ? mutation(mutation_context) : CLI_OK;ops->mutation_lease_release(ops->context, mutation_lease);if (rc != CLI_OK) {- cli_activation_diagnostic(ops, rc == CLI_ACTIVATION_PARTIAL- ? CLI_ACTIVATION_PARTIAL_MESSAGE+ cli_activation_diagnostic(ops, rc == CLI_ACTIVATION_PARTIAL ? CLI_ACTIVATION_PARTIAL_MESSAGE+ : rc == CLI_ACTIVATION_RUNTIME_ROLLED_BACK+ ? CLI_ACTIVATION_RUNTIME_ROLLED_BACK_MESSAGE: CLI_ACTIVATION_MUTATION_FAILED_MESSAGE);}return rc;@@ -723,9 +730,10 @@ static int cli_activation_guard(cbm_daemon_runtime_activation_action_t action,(void)cli_activation_log_event(&context, "failed",context.mutation_authorized- ? (rc == CLI_ACTIVATION_PARTIAL- ? "published/current binary retained; agent "- "configuration refresh or cleanup incomplete"+ ? (rc == CLI_ACTIVATION_PARTIAL ? "published/current binary retained; agent "+ "configuration refresh or cleanup incomplete"+ : rc == CLI_ACTIVATION_RUNTIME_ROLLED_BACK+ ? "previous runtime set restored; configuration writes may remain": "activation mutation failed; filesystem writes may ""have completed"): "cohort drain or coordination failed");@@ -1157,13 +1165,6 @@ static void cli_activation_transaction_finalize_committed_or_fail_stop(cli_activation_transaction_abort_or_fail_stop(transaction_io, component);}-static int cli_activation_transaction_commit_removal(cbm_activation_transaction_t *transaction) {- return transaction && cbm_activation_transaction_commit(transaction, NULL, NULL) ==- CBM_ACTIVATION_TRANSACTION_OK- ? CLI_OK- : CLI_ERR;-}-static bool cli_activation_transaction_expected_build(cbm_activation_transaction_t *transaction,cli_binary_validator_t *validator) {const char *staged = cbm_activation_transaction_staged_path(transaction);@@ -4704,9 +4705,10 @@ static bool cbm_write_owned_hook_script(const char *path, const char *script) {}/* ── Integration-template rendering ───────────────────────────── */-/* Script bodies are no longer compiled in (a block of shebang'd shell text- * inside an unsigned executable is exactly what AV classifiers score); they- * come from the hash-verified cbm-integrations.json via integration_assets.h+/* Script bodies are no longer compiled in: a block of shebang'd shell text+ * inside a native executable is unnecessary mixed-content and attack surface+ * with plausible static-classifier overlap. The bodies come from the+ * hash-verified cbm-integrations.json via integration_assets.h* and are materialized here by placeholder substitution. Byte-identity with* the old embedded builders is the migration contract: ownership checks* recognise previously written files only because the rendered bytes are@@ -5975,9 +5977,10 @@ static int cli_ensure_windows_user_path(const char *bin_dir, bool dry_run) {* LTO or function-section garbage collection to drop it.** "Download an archive, decompress it in memory, pick an executable out of it,- * write it to disk and mark it executable" is the canonical dropper composite.- * We do not do that in production, and now we cannot: the capability is not in- * the artifact rather than merely unreachable within it. Verified by+ * write it to disk and mark it executable" is a high-risk dual-use capability+ * commonly associated with installer and loader behavior. We do not do that+ * in production, and now we cannot: the capability is not in the artifact+ * rather than merely unreachable within it. Verified by* scripts/ci/check-binary-composition.sh.*/#ifdef CBM_CLI_ENABLE_TEST_API@@ -9034,13 +9037,16 @@ static bool cbm_detect_self_path(char *buf, size_t buf_sz, const char *home) {buf[0] = '\0';bool exact = false;#ifdef _WIN32- DWORD length = GetModuleFileNameA(NULL, buf, (DWORD)buf_sz);- exact = length > 0 && (size_t)length < buf_sz;+ char *module_path = cbm_module_path_utf8();+ size_t length = module_path ? strlen(module_path) : 0U;+ exact = module_path && length > 0U && length < buf_sz;if (exact) {+ memcpy(buf, module_path, length + 1U);cbm_normalize_path_sep(buf);} else {buf[0] = '\0';}+ free(module_path);#elif defined(__APPLE__)uint32_t sp_sz = (uint32_t)buf_sz;exact = _NSGetExecutablePath(buf, &sp_sz) == 0;@@ -9056,7 +9062,7 @@ static bool cbm_detect_self_path(char *buf, size_t buf_sz, const char *home) {buf[0] = '\0';}#endif- if (!buf[0]) {+ if (!buf[0] && home && home[0]) {#ifdef _WIN32snprintf(buf, buf_sz, "%s/.local/bin/codebase-memory-mcp.exe", home);#else@@ -9066,6 +9072,73 @@ static bool cbm_detect_self_path(char *buf, size_t buf_sz, const char *home) {return exact;}+static bool cli_runtime_asset_regular_leaf(const char *path) {+ cbm_path_info_t info;+ return path && cbm_path_info_utf8(path, &info) == 0 && info.is_regular && !info.is_symlink;+}++bool cbm_cli_verify_runtime_assets_at(const char *binary_path, char *err, size_t err_sz) {+ if (!binary_path || !binary_path[0]) {+ if (err && err_sz > 0U) {+ (void)snprintf(err, err_sz, "runtime executable path is unavailable");+ }+ return false;+ }+ char directory[CLI_BUF_4K];+ int directory_length = snprintf(directory, sizeof(directory), "%s", binary_path);+ char *separator = directory_length > 0 ? strrchr(directory, '/') : NULL;+#ifdef _WIN32+ char *backslash = directory_length > 0 ? strrchr(directory, '\\') : NULL;+ if (backslash && (!separator || backslash > separator)) {+ separator = backslash;+ }+#endif+ if (directory_length <= 0 || (size_t)directory_length >= sizeof(directory) || !separator ||+ separator == directory) {+ if (err && err_sz > 0U) {+ (void)snprintf(err, err_sz, "runtime executable directory is unavailable");+ }+ return false;+ }+ *separator = '\0';+ char integration[CLI_BUF_4K];+ int integration_length =+ snprintf(integration, sizeof(integration), "%s/%s", directory, CBM_INTEGRATIONS_ASSET_NAME);+ if (integration_length <= 0 || (size_t)integration_length >= sizeof(integration) ||+ !cli_runtime_asset_regular_leaf(integration) ||+ !cbm_integration_assets_verify_file(integration)) {+ if (err && err_sz > 0U) {+ (void)snprintf(err, err_sz, "adjacent integration assets do not match this binary");+ }+ return false;+ }+ if (cbm_ui_assets_supported()) {+ char pack[CLI_BUF_4K];+ int pack_length =+ snprintf(pack, sizeof(pack), "%s/%s", directory, cbm_ui_assets_current_pack_name());+ if (pack_length <= 0 || (size_t)pack_length >= sizeof(pack) ||+ !cli_runtime_asset_regular_leaf(pack) || !cbm_ui_assets_verify_file(pack)) {+ if (err && err_sz > 0U) {+ (void)snprintf(err, err_sz, "adjacent UI assets do not match this binary");+ }+ return false;+ }+ }+ return true;+}++int cbm_cmd_verify_runtime_assets(void) {+ const char *home = cbm_get_home_dir();+ char self_path[CLI_BUF_4K] = {0};+ char err[CLI_BUF_1K] = {0};+ if (!cbm_detect_self_path(self_path, sizeof(self_path), home) ||+ !cbm_cli_verify_runtime_assets_at(self_path, err, sizeof(err))) {+ (void)fprintf(stderr, "runtime asset verification failed%s%s\n", err[0] ? ": " : "", err);+ return CLI_TRUE;+ }+ return CLI_OK;+}+/* Build the agent.install.plan.v1 receipt (#388): a machine-readable list of* the config / instruction / skill / agent / hook files `install` WOULD write, produced by* running the real install dispatch in record-only mode (no mutation, no@@ -9186,6 +9259,98 @@ char *cbm_build_install_plan_json(const char *home, const char *binary_path) {return cbm_build_install_plan_json_options(home, binary_path, false);}+static bool cli_ui_pack_filename_digest(const char *name,+ char digest[CBM_SHA256_HEX_LEN + CLI_SKIP_ONE]) {+ static const char prefix[] = "cbm-ui-";+ static const char suffix[] = ".pack";+ size_t prefix_length = sizeof(prefix) - CLI_SKIP_ONE;+ size_t suffix_length = sizeof(suffix) - CLI_SKIP_ONE;+ size_t expected_length = prefix_length + CBM_SHA256_HEX_LEN + suffix_length;+ if (!name || strlen(name) != expected_length || strncmp(name, prefix, prefix_length) != 0 ||+ strcmp(name + expected_length - suffix_length, suffix) != 0) {+ return false;+ }+ for (size_t index = 0U; index < CBM_SHA256_HEX_LEN; index++) {+ char byte = name[prefix_length + index];+ if (!((byte >= '0' && byte <= '9') || (byte >= 'a' && byte <= 'f'))) {+ return false;+ }+ digest[index] = byte;+ }+ digest[CBM_SHA256_HEX_LEN] = '\0';+ return true;+}++/* Remove only content-addressed packs whose exact retained bytes hash to the+ * digest in their filename. The removal transaction first moves the snapshotted+ * entry to its private backup; hashing that backup binds verification and+ * deletion to one file identity. A mismatch is rolled back and preserved. */+static void cli_gc_stale_ui_asset_packs(const char *install_dir) {+ if (!install_dir || !install_dir[0]) {+ return;+ }+ const char *current_pack = cbm_ui_assets_current_pack_name();+ cbm_dir_t *directory = cbm_opendir(install_dir);+ if (!directory) {+ return;+ }+ cbm_dirent_t *entry;+ while ((entry = cbm_readdir(directory)) != NULL) {+ char expected_digest[CBM_SHA256_HEX_LEN + CLI_SKIP_ONE];+ if (!cli_ui_pack_filename_digest(entry->name, expected_digest) ||+ (current_pack && strcmp(entry->name, current_pack) == 0)) {+ continue;+ }+ char path[CLI_BUF_4K];+ int path_length = snprintf(path, sizeof(path), "%s/%s", install_dir, entry->name);+ if (path_length <= 0 || (size_t)path_length >= sizeof(path)) {+ continue;+ }+ cbm_path_info_t path_info;+ if (cbm_path_info_utf8(path, &path_info) != 0 || !path_info.is_regular ||+ path_info.is_symlink) {+ continue;+ }+ cbm_activation_transaction_t *removal = NULL;+ cbm_activation_transaction_status_t status =+ cbm_activation_transaction_stage_removal(path, &removal);+ if (status != CBM_ACTIVATION_TRANSACTION_OK || !removal) {+ (void)fprintf(stderr, "note: retained stale UI asset pack %s (cannot stage)\n",+ entry->name);+ if (removal) {+ (void)cbm_activation_transaction_close(&removal);+ }+ continue;+ }+ status = cbm_activation_transaction_commit(removal, NULL, NULL);+ const char *retained = cbm_activation_transaction_backup_path(removal);+ char actual_digest[CBM_SHA256_HEX_LEN + CLI_SKIP_ONE];+ bool owned =+ status == CBM_ACTIVATION_TRANSACTION_OK && retained &&+ cbm_cli_sha256_file(retained, actual_digest, sizeof(actual_digest)) == CLI_OK &&+ strcmp(actual_digest, expected_digest) == 0;+ if (!owned) {+ if (status == CBM_ACTIVATION_TRANSACTION_OK &&+ cbm_activation_transaction_rollback(removal) != CBM_ACTIVATION_TRANSACTION_OK) {+ cli_activation_cleanup_fail_stop(NULL, "stale_ui_pack_restore");+ }+ cli_activation_transaction_abort_or_fail_stop(&removal, "stale_ui_pack_preservation");+ continue;+ }+ status = cbm_activation_transaction_finalize(removal);+ if (status != CBM_ACTIVATION_TRANSACTION_OK &&+ status != CBM_ACTIVATION_TRANSACTION_DEFERRED) {+ cli_activation_transaction_abort_or_fail_stop(&removal,+ "stale_ui_pack_finalize_recovery");+ (void)fprintf(stderr, "note: retained stale UI asset pack %s (cleanup failed)\n",+ entry->name);+ continue;+ }+ cli_activation_transaction_abort_or_fail_stop(&removal, "stale_ui_pack_close");+ }+ cbm_closedir(directory);+}+typedef struct {const char *bin_target;const char *bin_dir;@@ -9193,15 +9358,55 @@ typedef struct {const char *shell_rc;const char *prepared_candidate;cbm_activation_transaction_t *binary_transaction;+ cbm_activation_transaction_t *integration_adjacent_transaction;+ cbm_activation_transaction_t *integration_ownership_transaction;+ cbm_activation_transaction_t *ui_pack_transaction;cli_binary_validator_t binary_validator;bool has_binary_validator;bool copy_binary;+ bool publish_runtime_assets;bool delete_indexes;bool skip_config;bool force;bool dry_run;} cli_install_activation_t;+static void cli_install_runtime_abort(cli_install_activation_t *activation, const char *component) {+ if (!activation) {+ return;+ }+ cli_activation_transaction_abort_or_fail_stop(&activation->binary_transaction, component);+ cli_activation_transaction_abort_or_fail_stop(&activation->ui_pack_transaction, component);+ cli_activation_transaction_abort_or_fail_stop(&activation->integration_ownership_transaction,+ component);+ cli_activation_transaction_abort_or_fail_stop(&activation->integration_adjacent_transaction,+ component);+}++static bool cli_install_commit_integration_asset(cbm_activation_transaction_t *transaction) {+ return !transaction ||+ cbm_integration_assets_commit_install(transaction) == CBM_ACTIVATION_TRANSACTION_OK;+}++static bool cli_install_commit_ui_asset(cbm_activation_transaction_t *transaction) {+ return !transaction ||+ cbm_ui_assets_commit_install(transaction) == CBM_ACTIVATION_TRANSACTION_OK;+}++static void cli_install_runtime_finalize(cli_install_activation_t *activation) {+ if (!activation) {+ return;+ }+ cli_activation_transaction_finalize_committed_or_fail_stop(+ &activation->integration_adjacent_transaction, "install_integration_adjacent_finalize");+ cli_activation_transaction_finalize_committed_or_fail_stop(+ &activation->integration_ownership_transaction, "install_integration_ownership_finalize");+ cli_activation_transaction_finalize_committed_or_fail_stop(&activation->ui_pack_transaction,+ "install_ui_pack_finalize");+ cli_activation_transaction_finalize_committed_or_fail_stop(&activation->binary_transaction,+ "install_transaction_finalize");+}+static int cli_install_activate(void *opaque) {cli_install_activation_t *activation = opaque;if (!activation || !activation->bin_target || !activation->bin_dir || !activation->home ||@@ -9216,25 +9421,60 @@ static int cli_install_activate(void *opaque) {printf("Would install binary -> %s\n\n", activation->bin_target);}}- if (!activation->dry_run && !activation->binary_transaction && activation->prepared_candidate) {+ /* Candidate bytes may be prepared and fingerprinted before maintenance,+ * but the target snapshot must be taken after the lease is acquired. A+ * concurrent winner can legitimately change the target while this install+ * is waiting. Re-stage from the immutable private candidate/old stage into+ * a fresh final transaction on every guarded activation. */+ if (!activation->dry_run &&+ (activation->binary_transaction || activation->prepared_candidate)) {if (!cbm_mkdir_p(activation->bin_dir, CLI_OCTAL_PERM)) {(void)fprintf(stderr, "error: cannot create install directory %s\n",activation->bin_dir);return CLI_TRUE;}+ cbm_activation_transaction_t *pre_guard_transaction = activation->binary_transaction;+ const char *restage_source =+ activation->prepared_candidate+ ? activation->prepared_candidate+ : cbm_activation_transaction_staged_path(pre_guard_transaction);+ cbm_activation_transaction_t *guarded_transaction = NULL;cbm_activation_transaction_status_t stage_status = cbm_activation_transaction_stage_file(- activation->bin_target, activation->prepared_candidate,- &activation->binary_transaction);+ activation->bin_target, restage_source, &guarded_transaction);cli_binary_validator_t restaged_validator = {{0}};- if (stage_status != CBM_ACTIVATION_TRANSACTION_OK || !activation->binary_transaction ||- !cli_activation_transaction_expected_build(activation->binary_transaction,- &restaged_validator) ||+ if (stage_status != CBM_ACTIVATION_TRANSACTION_OK || !guarded_transaction ||+ !cli_activation_transaction_expected_build(guarded_transaction, &restaged_validator) ||!activation->has_binary_validator ||strcmp(restaged_validator.fingerprint, activation->binary_validator.fingerprint) != 0) {(void)fprintf(stderr, "error: verified install candidate could not be ""re-staged on the target filesystem\n");- cli_activation_transaction_abort_or_fail_stop(&activation->binary_transaction,- "install_transaction_restaging_cleanup");+ cli_activation_transaction_abort_or_fail_stop(&guarded_transaction,+ "install_guarded_restaging_cleanup");+ return CLI_TRUE;+ }+ activation->binary_transaction = guarded_transaction;+ cli_activation_transaction_abort_or_fail_stop(&pre_guard_transaction,+ "install_pre_guard_stage_cleanup");+ }++ if (!activation->dry_run && activation->publish_runtime_assets) {+ char asset_error[CLI_BUF_1K] = {0};+ if (!cbm_integration_assets_stage_install(activation->home, activation->bin_dir,+ &activation->integration_adjacent_transaction,+ &activation->integration_ownership_transaction,+ asset_error, sizeof(asset_error)) ||+ !cbm_ui_assets_stage_install(activation->bin_dir, &activation->ui_pack_transaction,+ asset_error, sizeof(asset_error))) {+ cli_install_runtime_abort(activation, "install_runtime_asset_stage_cleanup");+ (void)fprintf(stderr, "error: %s\n",+ asset_error[0] ? asset_error : "failed to stage runtime assets");+ return CLI_TRUE;+ }+ if (!cli_install_commit_integration_asset(activation->integration_adjacent_transaction) ||+ !cli_install_commit_integration_asset(activation->integration_ownership_transaction) ||+ !cli_install_commit_ui_asset(activation->ui_pack_transaction)) {+ cli_install_runtime_abort(activation, "install_runtime_asset_publish_recovery");+ (void)fprintf(stderr, "error: failed to publish the staged runtime assets\n");return CLI_TRUE;}}@@ -9243,8 +9483,7 @@ static int cli_install_activate(void *opaque) {activation->binary_transaction,activation->has_binary_validator ? &activation->binary_validator : NULL,CLI_OCTAL_PERM) != CLI_OK) {- cli_activation_transaction_abort_or_fail_stop(&activation->binary_transaction,- "install_transaction_publish_recovery");+ cli_install_runtime_abort(activation, "install_transaction_publish_recovery");(void)fprintf(stderr, "error: failed to publish the staged binary to %s\n",activation->bin_target);return CLI_TRUE;@@ -9262,12 +9501,11 @@ static int cli_install_activate(void *opaque) {activation->dry_run);}if (agent_config_rc != CLI_OK) {- cli_activation_transaction_finalize_committed_or_fail_stop(- &activation->binary_transaction, "install_transaction_partial_finalize");- (void)fprintf(stderr, "error: one or more agent configurations failed; the "- "published/current executable was kept, and PATH/index cleanup "- "was not attempted\n");- return CLI_ACTIVATION_PARTIAL;+ cli_install_runtime_abort(activation, "install_config_failure_rollback");+ (void)fprintf(stderr, "error: one or more agent configurations failed; the previous "+ "runtime set was restored, and PATH/index cleanup was not "+ "attempted\n");+ return CLI_ACTIVATION_RUNTIME_ROLLED_BACK;}int path_rc = CLI_TRUE;#ifdef _WIN32@@ -9289,26 +9527,26 @@ static int cli_install_activate(void *opaque) {}#endifif (path_rc == CLI_ERR) {- cli_activation_transaction_finalize_committed_or_fail_stop(- &activation->binary_transaction, "install_transaction_path_failure_finalize");- (void)fprintf(stderr, "error: PATH configuration failed; the published/current "- "executable was kept, and index cleanup was not attempted\n");- return CLI_ACTIVATION_PARTIAL;+ cli_install_runtime_abort(activation, "install_path_failure_rollback");+ (void)fprintf(stderr, "error: PATH configuration failed; the previous runtime set was "+ "restored, and index cleanup was not attempted\n");+ return CLI_ACTIVATION_RUNTIME_ROLLED_BACK;}if (!activation->dry_run && activation->delete_indexes) {int expected = count_db_indexes(activation->home);int removed = cbm_remove_indexes(activation->home);printf("Removed %d index(es).\n\n", removed);if (removed != expected) {- cli_activation_transaction_finalize_committed_or_fail_stop(- &activation->binary_transaction, "install_transaction_index_failure_finalize");+ cli_install_runtime_abort(activation, "install_index_failure_rollback");(void)fprintf(stderr, "error: only %d of %d indexes could be removed\n", removed,expected);- return CLI_ACTIVATION_PARTIAL;+ return CLI_ACTIVATION_RUNTIME_ROLLED_BACK;}}- cli_activation_transaction_finalize_committed_or_fail_stop(&activation->binary_transaction,- "install_transaction_finalize");+ if (!activation->dry_run && activation->publish_runtime_assets) {+ cli_gc_stale_ui_asset_packs(activation->bin_dir);+ }+ cli_install_runtime_finalize(activation);return CLI_OK;}@@ -9391,27 +9629,14 @@ int cbm_cmd_install(int argc, char **argv) {return 0;}- /* Integration-assets gate: verify cbm-integrations.json against the- * embedded SHA-256 BEFORE the first mutation and persist the verified- * copy to <home>/.cbm/assets/<version>/ (the ownership reference for- * every later upgrade/uninstall decision). Missing or modified assets- * fail the whole install with one actionable message — never a partial- * install, and --dry-run must not promise what a real run would refuse. */- {- char assets_error[CLI_BUF_1K];- if (!cbm_integration_assets_install(home, dry_run, assets_error, sizeof(assets_error))) {- (void)fprintf(stderr, "error: %s\n", assets_error);- return CLI_TRUE;- }- }-- printf("codebase-memory-mcp install %s\n\n", CBM_VERSION);-char self_path[CLI_BUF_1K] = {0};(void)cbm_detect_self_path(self_path, sizeof(self_path), home);+ cbm_ui_assets_set_binary_path(self_path);- struct stat target_status;- bool target_exists = (stat(bin_target, &target_status) == 0);+ printf("codebase-memory-mcp install %s\n\n", CBM_VERSION);++ cbm_path_info_t target_status;+ bool target_exists = cbm_path_info_utf8(bin_target, &target_status) == 0;bool same_binary = cbm_same_file(self_path, bin_target);bool do_copy = !same_binary && (!target_exists || force);@@ -9437,13 +9662,34 @@ int cbm_cmd_install(int argc, char **argv) {printf("Keeping existing binary; configs will point at it.\n\n");}}+ /* A retained, different target must keep the sidecars compiled for that+ * target. Publishing this process's assets would create a cross-build+ * runtime set even though the user explicitly declined the binary. */+ bool publish_runtime_assets = same_binary || do_copy;++ /* Config generation needs the integration templates. Runtime publication+ * additionally needs the UI pack. Resolve only what this invocation will+ * actually consume, after the replacement decision is final. */+ {+ char assets_error[CLI_BUF_1K];+ if ((publish_runtime_assets || !skip_config) &&+ !cbm_integration_assets_require(home, assets_error, sizeof(assets_error))) {+ (void)fprintf(stderr, "error: %s\n", assets_error);+ return CLI_TRUE;+ }+ if (publish_runtime_assets &&+ !cbm_ui_assets_warm(home, assets_error, sizeof(assets_error))) {+ (void)fprintf(stderr, "error: %s\n", assets_error);+ return CLI_TRUE;+ }+ }#ifdef __APPLE__/* A freshly clang-built arm64 binary is linker-signed (flags=0x20002)* and gets Killed:9 when spawned by an MCP host. Sign the private staged* candidate before disrupting sessions, then publish those exact verified* bytes inside the activation window. */- bool sign_binary = do_copy || target_exists;- bool prepare_binary = sign_binary;+ bool sign_binary = do_copy;+ bool prepare_binary = do_copy;#elsebool prepare_binary = do_copy;#endif@@ -9459,40 +9705,31 @@ int cbm_cmd_install(int argc, char **argv) {/* Non-macOS activation reaches this block only for a real copy. */const char *candidate = self_path;#endif- bool target_parent_exists = cbm_is_dir(bin_dir);- bool prepare_out_of_line = !target_parent_exists;-#ifdef __APPLE__- /* codesign may replace the file's inode. Sign a private published copy- * first, then open the final transaction over those immutable bytes;- * mutating a transaction-owned stage invalidates its identity snapshot. */- prepare_out_of_line = prepare_out_of_line || sign_binary;-#endif- const char *stage_target = bin_target;- if (prepare_out_of_line) {- int dir_length =- snprintf(prepared_dir, sizeof(prepared_dir), "%s/cbm-install-XXXXXX", cbm_tmpdir());- if (dir_length <= 0 || (size_t)dir_length >= sizeof(prepared_dir) ||- !cbm_mkdtemp(prepared_dir)) {- (void)fprintf(stderr, "error: cannot create private install staging "- "directory\n");- return CLI_TRUE;- }+ /* Preparation is always out-of-line. The target transaction must not+ * snapshot or reserve anything in the install directory until the+ * activation guard is held; otherwise a waiter races the current+ * winner and carries a stale target snapshot into commit. */+ int dir_length =+ snprintf(prepared_dir, sizeof(prepared_dir), "%s/cbm-install-XXXXXX", cbm_tmpdir());+ if (dir_length <= 0 || (size_t)dir_length >= sizeof(prepared_dir) ||+ !cbm_mkdtemp(prepared_dir)) {+ (void)fprintf(stderr, "error: cannot create private install staging directory\n");+ return CLI_TRUE;+ }#ifdef _WIN32- int candidate_length = snprintf(prepared_candidate, sizeof(prepared_candidate),- "%s/codebase-memory-mcp.exe", prepared_dir);+ int candidate_length = snprintf(prepared_candidate, sizeof(prepared_candidate),+ "%s/codebase-memory-mcp.exe", prepared_dir);#else- int candidate_length = snprintf(prepared_candidate, sizeof(prepared_candidate),- "%s/codebase-memory-mcp", prepared_dir);+ int candidate_length = snprintf(prepared_candidate, sizeof(prepared_candidate),+ "%s/codebase-memory-mcp", prepared_dir);#endif- if (candidate_length <= 0 || (size_t)candidate_length >= sizeof(prepared_candidate)) {- (void)cbm_rmdir(prepared_dir);- (void)fprintf(stderr, "error: private install staging path is too long\n");- return CLI_TRUE;- }- stage_target = prepared_candidate;+ if (candidate_length <= 0 || (size_t)candidate_length >= sizeof(prepared_candidate)) {+ (void)cbm_rmdir(prepared_dir);+ (void)fprintf(stderr, "error: private install staging path is too long\n");+ return CLI_TRUE;}- cbm_activation_transaction_status_t stage_status =- cbm_activation_transaction_stage_file(stage_target, candidate, &binary_transaction);+ cbm_activation_transaction_status_t stage_status = cbm_activation_transaction_stage_file(+ prepared_candidate, candidate, &binary_transaction);cli_binary_validator_t staged_validator = {{0}};if (stage_status != CBM_ACTIVATION_TRANSACTION_OK || !binary_transaction ||!cli_activation_transaction_expected_build(binary_transaction, &staged_validator)) {@@ -9506,70 +9743,33 @@ int cbm_cmd_install(int argc, char **argv) {}return CLI_TRUE;}- if (prepare_out_of_line) {- if (cli_activation_transaction_commit_validated(binary_transaction, &staged_validator,- CLI_OCTAL_PERM) != CLI_OK ||- cli_activation_transaction_finalize_close(&binary_transaction) != CLI_OK) {- (void)cli_activation_transaction_abort(&binary_transaction);- (void)cbm_unlink(prepared_candidate);- (void)cbm_rmdir(prepared_dir);- (void)fprintf(stderr, "error: private install candidate preparation "- "failed\n");- return CLI_TRUE;- }+ if (cli_activation_transaction_commit_validated(binary_transaction, &staged_validator,+ CLI_OCTAL_PERM) != CLI_OK ||+ cli_activation_transaction_finalize_close(&binary_transaction) != CLI_OK) {+ (void)cli_activation_transaction_abort(&binary_transaction);+ (void)cbm_unlink(prepared_candidate);+ (void)cbm_rmdir(prepared_dir);+ (void)fprintf(stderr, "error: private install candidate preparation failed\n");+ return CLI_TRUE;+ }#ifdef __APPLE__- if (sign_binary && cbm_macos_adhoc_sign(prepared_candidate) != 0) {- (void)fprintf(stderr, "error: ad-hoc signing the private macOS candidate failed\n");- (void)cbm_unlink(prepared_candidate);- (void)cbm_rmdir(prepared_dir);- return CLI_TRUE;- }+ if (sign_binary && cbm_macos_adhoc_sign(prepared_candidate) != 0) {+ (void)fprintf(stderr, "error: ad-hoc signing the private macOS candidate failed\n");+ (void)cbm_unlink(prepared_candidate);+ (void)cbm_rmdir(prepared_dir);+ return CLI_TRUE;+ }#endif- has_binary_validator =- cbm_daemon_build_fingerprint_file(prepared_candidate, binary_validator.fingerprint);- if (has_binary_validator && !g_cli_activation_test_ops_set) {- const char *candidate_argv[] = {prepared_candidate, "--version", NULL};- has_binary_validator = cbm_exec_no_shell(candidate_argv) == CLI_OK;- }- if (!has_binary_validator) {- (void)fprintf(stderr, "error: prepared install candidate could not be "- "verified\n");- (void)cbm_unlink(prepared_candidate);- (void)cbm_rmdir(prepared_dir);- return CLI_TRUE;- }- if (target_parent_exists) {- stage_status = cbm_activation_transaction_stage_file(bin_target, prepared_candidate,- &binary_transaction);- cli_binary_validator_t final_validator = {{0}};- if (stage_status != CBM_ACTIVATION_TRANSACTION_OK || !binary_transaction ||- !cli_activation_transaction_expected_build(binary_transaction,- &final_validator) ||- strcmp(final_validator.fingerprint, binary_validator.fingerprint) != 0) {- (void)fprintf(stderr, "error: signed install candidate could not be staged "- "on the target filesystem\n");- (void)cli_activation_transaction_abort(&binary_transaction);- (void)cbm_unlink(prepared_candidate);- (void)cbm_rmdir(prepared_dir);- return CLI_TRUE;- }- binary_validator = final_validator;- }- } else {- binary_validator = staged_validator;- has_binary_validator = true;+ has_binary_validator =+ cbm_daemon_build_fingerprint_file(prepared_candidate, binary_validator.fingerprint);+ if (has_binary_validator && !g_cli_activation_test_ops_set) {+ const char *candidate_argv[] = {prepared_candidate, "--version", NULL};+ has_binary_validator = cbm_exec_no_shell(candidate_argv) == CLI_OK;}if (!has_binary_validator) {- (void)fprintf(stderr, "error: staged install candidate could not be verified\n");- if (binary_transaction) {- (void)cli_activation_transaction_abort(&binary_transaction);- }- if (prepared_candidate[0]) {- (void)cbm_unlink(prepared_candidate);- }- if (prepared_dir[0]) {- (void)cbm_rmdir(prepared_dir);- }+ (void)fprintf(stderr, "error: prepared install candidate could not be verified\n");+ (void)cbm_unlink(prepared_candidate);+ (void)cbm_rmdir(prepared_dir);return CLI_TRUE;}}@@ -9587,6 +9787,7 @@ int cbm_cmd_install(int argc, char **argv) {.binary_validator = binary_validator,.has_binary_validator = has_binary_validator,.copy_binary = do_copy,+ .publish_runtime_assets = publish_runtime_assets,.delete_indexes = delete_indexes,.skip_config = skip_config,.force = force,@@ -9597,9 +9798,7 @@ int cbm_cmd_install(int argc, char **argv) {: cli_activation_guard(CBM_DAEMON_RUNTIME_ACTIVATION_INSTALL, CBM_VERSION,has_binary_validator ? binary_validator.fingerprint : NULL,cli_install_activate, &activation);- if (activation.binary_transaction) {- (void)cli_activation_transaction_abort(&activation.binary_transaction);- }+ cli_install_runtime_abort(&activation, "install_runtime_post_guard_cleanup");if (prepared_candidate[0]) {(void)cbm_unlink(prepared_candidate);}@@ -10723,13 +10922,58 @@ static void uninstall_additional_agents(const cbm_detected_agents_t *agents, contypedef struct {const char *home;const char *bin_path;+ const char *bin_dir;cbm_activation_transaction_t *binary_transaction;+ cbm_activation_transaction_t *integration_adjacent_transaction;+ cbm_activation_transaction_t *integration_ownership_transaction;+ cbm_activation_transaction_t *ui_pack_transaction;cbm_detected_agents_t agents;bool binary_exists;+ bool foreign_integration_preserved;+ bool foreign_ui_pack_preserved;bool delete_indexes;bool dry_run;} cli_uninstall_activation_t;+static void cli_uninstall_runtime_abort(cli_uninstall_activation_t *activation,+ const char *component) {+ if (!activation) {+ return;+ }+ cli_activation_transaction_abort_or_fail_stop(&activation->ui_pack_transaction, component);+ cli_activation_transaction_abort_or_fail_stop(&activation->integration_ownership_transaction,+ component);+ cli_activation_transaction_abort_or_fail_stop(&activation->integration_adjacent_transaction,+ component);+ cli_activation_transaction_abort_or_fail_stop(&activation->binary_transaction, component);+}++static bool cli_uninstall_commit_removal(cbm_activation_transaction_t *transaction) {+ return !transaction || cbm_activation_transaction_commit(transaction, NULL, NULL) ==+ CBM_ACTIVATION_TRANSACTION_OK;+}++static bool cli_uninstall_commit_integration_removal(cbm_activation_transaction_t *transaction) {+ return !transaction ||+ cbm_integration_assets_commit_removal(transaction) == CBM_ACTIVATION_TRANSACTION_OK;+}++static bool cli_uninstall_commit_ui_removal(cbm_activation_transaction_t *transaction) {+ return !transaction ||+ cbm_ui_assets_commit_removal(transaction) == CBM_ACTIVATION_TRANSACTION_OK;+}++static void cli_uninstall_runtime_finalize(cli_uninstall_activation_t *activation) {+ cli_activation_transaction_finalize_committed_or_fail_stop(&activation->ui_pack_transaction,+ "uninstall_ui_pack_finalize");+ cli_activation_transaction_finalize_committed_or_fail_stop(+ &activation->integration_ownership_transaction, "uninstall_integration_owner_finalize");+ cli_activation_transaction_finalize_committed_or_fail_stop(+ &activation->integration_adjacent_transaction, "uninstall_integration_adjacent_finalize");+ cli_activation_transaction_finalize_committed_or_fail_stop(&activation->binary_transaction,+ "uninstall_binary_finalize");+}+/* Report — never delete — the updater script sitting next to the binary.** install.sh/install.ps1 copies itself beside the executable so `update` has@@ -10799,40 +11043,82 @@ static int cli_uninstall_activate(void *opaque) {uninstall_agent_client_registry(activation->home, activation->dry_run);if (g_agent_uninstall_errors != 0) {- cli_activation_transaction_abort_or_fail_stop(&activation->binary_transaction,- "uninstall_transaction_config_cleanup_abort");+ cli_uninstall_runtime_abort(activation, "uninstall_transaction_config_cleanup_abort");(void)fprintf(stderr, "error: one or more agent cleanup operations failed; executable ""and index removal were not started\n");return CLI_ACTIVATION_PARTIAL;}+ /* All removal staging belongs inside the activation guard: staging creates+ * durable sibling reservations even though it does not yet move targets. */+ if (!activation->dry_run) {+ cbm_path_info_t binary_info;+ activation->binary_exists = cbm_path_info_utf8(activation->bin_path, &binary_info) == 0;+ if (activation->binary_exists) {+ cbm_activation_transaction_status_t status = cbm_activation_transaction_stage_removal(+ activation->bin_path, &activation->binary_transaction);+ if (status != CBM_ACTIVATION_TRANSACTION_OK || !activation->binary_transaction) {+ cli_uninstall_runtime_abort(activation, "uninstall_binary_stage_cleanup");+ (void)fprintf(stderr, "error: failed to stage uninstall transaction: %s\n",+ cbm_activation_transaction_status_message(status));+ return CLI_ACTIVATION_PARTIAL;+ }+ }+ char asset_error[CLI_BUF_1K] = {0};+ if (!cbm_integration_assets_stage_remove(activation->home, activation->bin_dir,+ &activation->integration_adjacent_transaction,+ &activation->integration_ownership_transaction,+ &activation->foreign_integration_preserved,+ asset_error, sizeof(asset_error)) ||+ !cbm_ui_assets_stage_remove(activation->bin_dir, &activation->ui_pack_transaction,+ &activation->foreign_ui_pack_preserved, asset_error,+ sizeof(asset_error))) {+ cli_uninstall_runtime_abort(activation, "uninstall_runtime_asset_stage_cleanup");+ (void)fprintf(stderr, "error: %s\n",+ asset_error[0] ? asset_error : "failed to stage runtime asset removal");+ return CLI_ACTIVATION_PARTIAL;+ }+ }+if (activation->delete_indexes && !activation->dry_run) {int expected = count_db_indexes(activation->home);int idx_removed = cbm_remove_indexes(activation->home);printf("Removed %d index(es).\n", idx_removed);if (idx_removed != expected) {- cli_activation_transaction_abort_or_fail_stop(- &activation->binary_transaction, "uninstall_transaction_index_failure_abort");+ cli_uninstall_runtime_abort(activation, "uninstall_transaction_index_failure_abort");(void)fprintf(stderr, "error: only %d of %d indexes could be removed\n", idx_removed,expected);return CLI_ACTIVATION_PARTIAL;}}- if (!activation->dry_run && activation->binary_transaction) {- if (cli_activation_transaction_commit_removal(activation->binary_transaction) != CLI_OK) {- cli_activation_transaction_abort_or_fail_stop(&activation->binary_transaction,- "uninstall_transaction_removal_recovery");+ if (!activation->dry_run) {+ /* Remove the executable first. A crash during the subsequent sidecar+ * removals can leave inert data behind, never a runnable binary with a+ * partial runtime set. Cooperative failures roll every commit back. */+ if (!cli_uninstall_commit_removal(activation->binary_transaction) ||+ !cli_uninstall_commit_integration_removal(+ activation->integration_adjacent_transaction) ||+ !cli_uninstall_commit_integration_removal(+ activation->integration_ownership_transaction) ||+ !cli_uninstall_commit_ui_removal(activation->ui_pack_transaction)) {+ cli_uninstall_runtime_abort(activation, "uninstall_transaction_removal_recovery");(void)fprintf(stderr,- "error: failed to remove %s; completed "+ "error: failed to remove the owned runtime set for %s; completed ""configuration/index cleanup may remain\n",activation->bin_path);return CLI_ACTIVATION_PARTIAL;}- cli_activation_transaction_finalize_committed_or_fail_stop(- &activation->binary_transaction, "uninstall_transaction_removal_finalize");+ cli_uninstall_runtime_finalize(activation);}if (activation->binary_exists) {- printf("Removed %s\n", activation->bin_path);+ printf("%s %s\n", activation->dry_run ? "Would remove" : "Removed", activation->bin_path);+ }+ if (activation->foreign_integration_preserved) {+ (void)fprintf(stderr, "note: a modified or foreign %s was preserved\n",+ CBM_INTEGRATIONS_ASSET_NAME);+ }+ if (activation->foreign_ui_pack_preserved) {+ (void)fprintf(stderr, "note: a modified or foreign UI asset pack was preserved\n");}cli_uninstall_report_leftover_installer(activation->bin_path, activation->dry_run);return CLI_OK;@@ -10841,6 +11127,7 @@ static int cli_uninstall_activate(void *opaque) {int cbm_cmd_uninstall(int argc, char **argv) {parse_auto_answer(argc, argv);bool dry_run = false;+ const char *requested_bin_dir = NULL;for (int i = 0; i < argc; i++) {/* The public command dispatcher passes option-only argv, while the* long-standing direct API/tests include the subcommand at argv[0]. */@@ -10849,6 +11136,18 @@ int cbm_cmd_uninstall(int argc, char **argv) {}if (strcmp(argv[i], "--dry-run") == 0) {dry_run = true;+ } else if (strncmp(argv[i], "--dir=", SLEN("--dir=")) == 0) {+ requested_bin_dir = argv[i] + SLEN("--dir=");+ if (!requested_bin_dir[0]) {+ (void)fprintf(stderr, "error: --dir requires a non-empty path\n");+ return CLI_TRUE;+ }+ } else if (strcmp(argv[i], "--dir") == 0) {+ if (i + 1 >= argc || !argv[i + 1] || !argv[i + 1][0] || argv[i + 1][0] == '-') {+ (void)fprintf(stderr, "error: --dir requires a non-empty path\n");+ return CLI_TRUE;+ }+ requested_bin_dir = argv[++i];} else if (strcmp(argv[i], "-y") != 0 && strcmp(argv[i], "--yes") != 0 &&strcmp(argv[i], "-n") != 0 && strcmp(argv[i], "--no") != 0) {(void)fprintf(stderr, "error: unknown uninstall option: %s\n", argv[i]);@@ -10897,31 +11196,89 @@ int cbm_cmd_uninstall(int argc, char **argv) {}}- char bin_path_storage[CLI_BUF_1K];- const char *bin_path = bin_path_storage;+ char bin_dir_storage[CLI_BUF_1K] = {0};+ char bin_path_storage[CLI_BUF_1K] = {0};+ bool use_self_path = false;+ if (!requested_bin_dir) {+ char self_path[CLI_BUF_1K] = {0};+ if (cbm_detect_self_path(self_path, sizeof(self_path), home)) {+ const char *base = strrchr(self_path, '/');#ifdef _WIN32- snprintf(bin_path_storage, sizeof(bin_path_storage), "%s/.local/bin/codebase-memory-mcp.exe",- home);+ const char *backslash = strrchr(self_path, '\\');+ if (backslash && (!base || backslash > base)) {+ base = backslash;+ }+#endif+ base = base ? base + CLI_SKIP_ONE : self_path;+#ifdef _WIN32+ use_self_path = strcmp(base, "codebase-memory-mcp.exe") == 0;#else- snprintf(bin_path_storage, sizeof(bin_path_storage), "%s/.local/bin/codebase-memory-mcp", home);+ use_self_path = strcmp(base, "codebase-memory-mcp") == 0;#endif- struct stat binary_status;- bool binary_exists = stat(bin_path, &binary_status) == 0;- cbm_activation_transaction_t *binary_transaction = NULL;- if (!dry_run && binary_exists) {- cbm_activation_transaction_status_t stage_status =- cbm_activation_transaction_stage_removal(bin_path, &binary_transaction);- if (stage_status != CBM_ACTIVATION_TRANSACTION_OK || !binary_transaction) {- (void)fprintf(stderr, "error: failed to stage uninstall transaction: %s\n",- cbm_activation_transaction_status_message(stage_status));- (void)cli_activation_transaction_abort(&binary_transaction);+ if (use_self_path) {+ int path_length =+ snprintf(bin_path_storage, sizeof(bin_path_storage), "%s", self_path);+ char *separator = strrchr(bin_path_storage, '/');+#ifdef _WIN32+ char *path_backslash = strrchr(bin_path_storage, '\\');+ if (path_backslash && (!separator || path_backslash > separator)) {+ separator = path_backslash;+ }+#endif+ if (path_length <= 0 || (size_t)path_length >= sizeof(bin_path_storage) ||+ !separator || separator == bin_path_storage) {+ (void)fprintf(stderr, "error: cannot resolve current install directory\n");+ return CLI_TRUE;+ }+ size_t directory_length = (size_t)(separator - bin_path_storage);+ if (directory_length >= sizeof(bin_dir_storage)) {+ (void)fprintf(stderr, "error: current install directory path is too long\n");+ return CLI_TRUE;+ }+ memcpy(bin_dir_storage, bin_path_storage, directory_length);+ bin_dir_storage[directory_length] = '\0';+ }+ }+ }+ if (!use_self_path) {+ int directory_length;+ if (requested_bin_dir) {+ directory_length =+ snprintf(bin_dir_storage, sizeof(bin_dir_storage), "%s", requested_bin_dir);+ } else {+#ifdef _WIN32+ const char *local = cbm_app_local_dir();+ directory_length = local ? snprintf(bin_dir_storage, sizeof(bin_dir_storage),+ "%s/Programs/codebase-memory-mcp", local)+ : -1;+#else+ directory_length =+ snprintf(bin_dir_storage, sizeof(bin_dir_storage), "%s/.local/bin", home);+#endif+ }+ if (directory_length <= 0 || (size_t)directory_length >= sizeof(bin_dir_storage)) {+ (void)fprintf(stderr, "error: uninstall directory path is unavailable or too long\n");+ return CLI_TRUE;+ }+ cbm_normalize_path_sep(bin_dir_storage);+#ifdef _WIN32+ int target_length = snprintf(bin_path_storage, sizeof(bin_path_storage),+ "%s/codebase-memory-mcp.exe", bin_dir_storage);+#else+ int target_length = snprintf(bin_path_storage, sizeof(bin_path_storage),+ "%s/codebase-memory-mcp", bin_dir_storage);+#endif+ if (target_length <= 0 || (size_t)target_length >= sizeof(bin_path_storage)) {+ (void)fprintf(stderr, "error: uninstall target path is too long\n");return CLI_TRUE;}}+ cbm_path_info_t binary_info;+ bool binary_exists = cbm_path_info_utf8(bin_path_storage, &binary_info) == 0;cli_uninstall_activation_t activation = {.home = home,- .bin_path = bin_path,- .binary_transaction = binary_transaction,+ .bin_path = bin_path_storage,+ .bin_dir = bin_dir_storage,.agents = agents,.binary_exists = binary_exists,.delete_indexes = delete_indexes,@@ -10934,9 +11291,7 @@ int cbm_cmd_uninstall(int argc, char **argv) {activation_rc = cli_activation_guard(CBM_DAEMON_RUNTIME_ACTIVATION_UNINSTALL, NULL, NULL,cli_uninstall_activate, &activation);}- if (activation.binary_transaction) {- (void)cli_activation_transaction_abort(&activation.binary_transaction);- }+ cli_uninstall_runtime_abort(&activation, "uninstall_runtime_post_guard_cleanup");if (activation_rc != CLI_OK) {return CLI_TRUE;}@@ -11294,7 +11649,7 @@ static int select_update_variant(int variant_flag) {#endifprintf("Which binary variant do you want?\n");printf(" 1) standard — MCP server only\n");- printf(" 2) ui — MCP server + embedded graph visualization\n");+ printf(" 2) ui — MCP server + external graph-visualization assets\n");printf("Choose (1/2): ");(void)fflush(stdout);char choice[CLI_BUF_16];@@ -11408,15 +11763,16 @@ int cbm_cmd_update(int argc, char **argv) {** Windows forced the split first: a running .exe cannot replace itself, so* an in-process updater needed a second resident binary to swap the first- * one out, and that launcher stub was exactly the shape Defender's ML- * scores as a dropper.+ * one out. That launcher stub also combined verifier/launcher behavior in a+ * small executable, an unnecessary dropper-like surface.** The rest followed for the same reason rather than a different one. An* in-process updater is, structurally, a downloader: it fetches a remote- * archive, extracts it, marks the result executable and runs it. That is- * the behaviour Microsoft's Wacatac family describes almost verbatim, and- * carrying it in the product binary put download/extract/chmod/exec in- * every shipped artifact for a command most users run a handful of times.+ * archive, extracts it, marks the result executable and runs it. Those are+ * dual-use behaviors represented in malware-classification literature, but+ * their presence cannot attribute an opaque vendor verdict. Carrying them+ * in the product binary still put download/extract/chmod/exec in every+ * shipped artifact for a command most users run a handful of times.** The install script already does all of it, is idempotent -- so re-running* it IS the update -- and runs while cbm is NOT running. Print the exact@@ -11438,17 +11794,9 @@ int cbm_cmd_update(int argc, char **argv) {{char self_dir[CLI_BUF_1K] = {0};bool have_dir = false;-#ifdef _WIN32- /* Native separators on purpose: this path is printed for the user to- * paste into PowerShell verbatim. */- DWORD self_len = GetModuleFileNameA(NULL, self_dir, (DWORD)sizeof(self_dir));- char *last_sep =- (self_len > 0 && (size_t)self_len < sizeof(self_dir)) ? strrchr(self_dir, '\\') : NULL;-#elsechar *last_sep = cbm_detect_self_path(self_dir, sizeof(self_dir), cbm_get_home_dir())? strrchr(self_dir, '/'): NULL;-#endifif (last_sep) {*last_sep = '\0';have_dir = true;@@ -11467,7 +11815,7 @@ int cbm_cmd_update(int argc, char **argv) {printf("The update runs from install.ps1, not from this process. Close any\n""running sessions, then run\n\n");if (have_dir) {- printf(" powershell -File \"%s\\install.ps1\"\n\n", self_dir);+ printf(" powershell -File \"%s/install.ps1\"\n\n", self_dir);} else {printf(" powershell -File install.ps1\n"" (ships in the release archive, and is placed beside the\n"diff --git a/src/cli/cli.h b/src/cli/cli.hindex de4939c74..49cc79e51 100644--- a/src/cli/cli.h+++ b/src/cli/cli.h@@ -449,6 +449,11 @@ int cbm_cmd_install(int argc, char **argv);/* uninstall: remove skills, remove editor MCP configs, remove binary. */int cbm_cmd_uninstall(int argc, char **argv);+/* Hidden package-wrapper health probe. Verifies only immutable sidecars+ * adjacent to the running executable; never consults fallbacks or mutates. */+int cbm_cmd_verify_runtime_assets(void);+bool cbm_cli_verify_runtime_assets_at(const char *binary_path, char *err, size_t err_sz);+/* update: check latest release, prompt for index deletion, prompt for ui/standard,* download and replace binary. */int cbm_cmd_update(int argc, char **argv);diff --git a/src/cli/client_adapter.h b/src/cli/client_adapter.hindex b885d870a..6c9a96014 100644--- a/src/cli/client_adapter.h+++ b/src/cli/client_adapter.h@@ -8,9 +8,11 @@* - The module SCAFFOLDING (the node:child_process spawn bridge, header note,* plugin surface) comes from the hash-verified cbm-integrations.json via* integration_assets.h. It used to be compiled in as C string literals, but- * child-process-spawning script text inside an unsigned binary is exactly- * the surface AV classifiers score, so it ships as data and is verified- * against the binary's embedded SHA-256 before use.+ * child-process-spawning script text inside a native binary is unnecessary+ * mixed-content and attack surface with plausible static-classifier overlap.+ * It therefore ships as independently inspectable data and is verified+ * against the binary's embedded SHA-256 before use; this is not a claim of+ * feature attribution for any vendor verdict.** - The TOOL LIST is still generated at install time from the live registry* (cbm_mcp_tool_count / cbm_mcp_tool_name), never hand-maintained in thediff --git a/src/cli/integration_assets.c b/src/cli/integration_assets.cindex b8e8e296e..57e5328b2 100644--- a/src/cli/integration_assets.c+++ b/src/cli/integration_assets.c@@ -3,7 +3,7 @@** See integration_assets.h for the architecture (why the bodies live in a* data file, the integrity model, and the ownership-reference role of the- * stored copy under <home>/.cbm/assets/<version>/).+ * content-addressed stored copy under <home>/.cbm/assets/<sha256>/).*/#include "cli/integration_assets.h"@@ -12,6 +12,9 @@#include "foundation/constants.h"#include "foundation/platform.h"#include "foundation/sha256.h"+#ifdef _WIN32+#include "foundation/win_utf8.h"+#endif#include "yyjson/yyjson.h"#include "cbm_integrations_hash.h"@@ -19,6 +22,7 @@#include <stdio.h>#include <stdlib.h>#include <string.h>+#include <sys/stat.h>#ifndef _WIN32#include <unistd.h>@@ -27,12 +31,9 @@#include <mach-o/dyld.h>#endif-#ifndef CBM_VERSION-#define CBM_VERSION "dev"-#endif-enum {ASSETS_DIR_PERM = 0755,+ ASSETS_FILE_PERM = 0644,/* The shipped file is ~8 KB; the cap only bounds a corrupted candidate. */ASSETS_MAX_BYTES = CBM_SZ_64K * CBM_SZ_16,};@@ -41,8 +42,8 @@ enum {* reports the same recovery, because the recovery is always the same. */static const char assets_error_message[] ="integration assets missing or modified - reinstall from the release archive "- "(expected " CBM_INTEGRATIONS_ASSET_NAME " next to the binary, in $CBM_ASSETS_DIR, "- "or under ~/.cbm/assets/" CBM_VERSION ")";+ "(expected " CBM_INTEGRATIONS_ASSET_NAME " next to the binary, in its package share "+ "directory, in $CBM_ASSETS_DIR, or under ~/.cbm/assets/" CBM_INTEGRATIONS_SHA256 ")";typedef struct {const char *id;@@ -72,10 +73,14 @@ static bool assets_exe_dir(char *out, size_t out_sz) {return false;}#ifdef _WIN32- DWORD length = GetModuleFileNameA(NULL, out, (DWORD)out_sz);- if (length == 0 || (size_t)length >= out_sz) {+ char *module_path = cbm_module_path_utf8();+ size_t length = module_path ? strlen(module_path) : 0U;+ if (!module_path || length == 0U || length >= out_sz) {+ free(module_path);return false;}+ memcpy(out, module_path, length + 1U);+ free(module_path);cbm_normalize_path_sep(out);#elif defined(__APPLE__)uint32_t self_sz = (uint32_t)out_sz;@@ -97,11 +102,11 @@ static bool assets_exe_dir(char *out, size_t out_sz) {return true;}-static bool assets_stored_copy_path(const char *home, char *out, size_t out_sz) {+bool cbm_integration_assets_ownership_path(const char *home, char *out, size_t out_sz) {if (!home || !home[0]) {return false;}- int written = snprintf(out, out_sz, "%s/.cbm/assets/%s/%s", home, CBM_VERSION,+ int written = snprintf(out, out_sz, "%s/.cbm/assets/%s/%s", home, CBM_INTEGRATIONS_SHA256,CBM_INTEGRATIONS_ASSET_NAME);return written > 0 && (size_t)written < out_sz;}@@ -146,6 +151,15 @@ static bool assets_bytes_verified(const char *bytes, size_t length) {return strcmp(hex, CBM_INTEGRATIONS_SHA256) == 0;}+bool cbm_integration_assets_verify_file(const char *path) {+ char *bytes = NULL;+ size_t length = 0U;+ bool verified =+ path && assets_read_file(path, &bytes, &length) && assets_bytes_verified(bytes, length);+ free(bytes);+ return verified;+}+static bool assets_parse_body(yyjson_val *value, cbm_integration_body_t *body) {yyjson_val *text = yyjson_is_obj(value) ? yyjson_obj_get(value, "text") : NULL;yyjson_val *bin = yyjson_is_obj(value) ? yyjson_obj_get(value, "bin") : NULL;@@ -311,6 +325,13 @@ static bool assets_resolve(const char *home) {if (written > 0 && (size_t)written < sizeof(candidate) && assets_try_candidate(candidate)) {return true;}+ /* System package layout: <prefix>/bin/<binary> with the immutable+ * runtime asset under <prefix>/share/codebase-memory-mcp/. */+ written = snprintf(candidate, sizeof(candidate), "%s/../share/codebase-memory-mcp/%s",+ exe_dir, CBM_INTEGRATIONS_ASSET_NAME);+ if (written > 0 && (size_t)written < sizeof(candidate) && assets_try_candidate(candidate)) {+ return true;+ }/* Source-tree layout: build/c/<binary> with assets/ at the root. */written = snprintf(candidate, sizeof(candidate), "%s/../../assets/%s", exe_dir,CBM_INTEGRATIONS_ASSET_NAME);@@ -318,7 +339,7 @@ static bool assets_resolve(const char *home) {return true;}}- return assets_stored_copy_path(home, candidate, sizeof(candidate)) &&+ return cbm_integration_assets_ownership_path(home, candidate, sizeof(candidate)) &&assets_try_candidate(candidate);}@@ -330,6 +351,217 @@ bool cbm_integration_assets_require(const char *home, char *err, size_t err_sz)return false;}+static bool assets_transaction_close(cbm_activation_transaction_t **transaction_io) {+ return !transaction_io || !*transaction_io ||+ cbm_activation_transaction_close(transaction_io) == CBM_ACTIVATION_TRANSACTION_OK;+}++static bool assets_stage_target(const char *target, cbm_activation_transaction_t **transaction_out,+ char *err, size_t err_sz) {+ cbm_activation_transaction_status_t status = cbm_activation_transaction_stage_bytes(+ target, g_assets.bytes, g_assets.length, transaction_out);+ if (status == CBM_ACTIVATION_TRANSACTION_OK && *transaction_out) {+ return true;+ }+ if (err && err_sz > 0U) {+ (void)snprintf(err, err_sz, "cannot stage the verified %s copy for %s: %s",+ CBM_INTEGRATIONS_ASSET_NAME, target,+ cbm_activation_transaction_status_message(status));+ }+ (void)assets_transaction_close(transaction_out);+ return false;+}++static bool assets_install_validator(const char *target_path, void *context) {+ (void)context;+ return cbm_integration_assets_verify_file(target_path);+}++cbm_activation_transaction_status_t cbm_integration_assets_commit_install(+ cbm_activation_transaction_t *transaction) {+ if (!transaction) {+ return CBM_ACTIVATION_TRANSACTION_INVALID_ARGUMENT;+ }+ cbm_activation_transaction_status_t status =+ cbm_activation_transaction_commit(transaction, assets_install_validator, NULL);+#ifndef _WIN32+ if (status == CBM_ACTIVATION_TRANSACTION_OK) {+ const char *target = cbm_activation_transaction_target_path(transaction);+ if (!target || chmod(target, ASSETS_FILE_PERM) != 0) {+ cbm_activation_transaction_status_t rollback =+ cbm_activation_transaction_rollback(transaction);+ return rollback == CBM_ACTIVATION_TRANSACTION_OK+ ? CBM_ACTIVATION_TRANSACTION_IO+ : CBM_ACTIVATION_TRANSACTION_ROLLBACK_FAILED;+ }+ }+#endif+ return status;+}++cbm_activation_transaction_status_t cbm_integration_assets_commit_removal(+ cbm_activation_transaction_t *transaction) {+ if (!transaction) {+ return CBM_ACTIVATION_TRANSACTION_INVALID_ARGUMENT;+ }+ cbm_activation_transaction_status_t status =+ cbm_activation_transaction_commit(transaction, NULL, NULL);+ const char *retained = cbm_activation_transaction_backup_path(transaction);+ if (status != CBM_ACTIVATION_TRANSACTION_OK) {+ return status;+ }+ if (retained && cbm_integration_assets_verify_file(retained)) {+ return CBM_ACTIVATION_TRANSACTION_OK;+ }+ cbm_activation_transaction_status_t rollback = cbm_activation_transaction_rollback(transaction);+ return rollback == CBM_ACTIVATION_TRANSACTION_OK ? CBM_ACTIVATION_TRANSACTION_VALIDATION_FAILED+ : CBM_ACTIVATION_TRANSACTION_ROLLBACK_FAILED;+}++bool cbm_integration_assets_stage_install(const char *home, const char *install_dir,+ cbm_activation_transaction_t **adjacent_transaction_out,+ cbm_activation_transaction_t **ownership_transaction_out,+ char *err, size_t err_sz) {+ if (adjacent_transaction_out) {+ *adjacent_transaction_out = NULL;+ }+ if (ownership_transaction_out) {+ *ownership_transaction_out = NULL;+ }+ if (!home || !home[0] || !install_dir || !install_dir[0] || !adjacent_transaction_out ||+ !ownership_transaction_out || !cbm_integration_assets_require(home, err, err_sz)) {+ if ((!home || !home[0] || !install_dir || !install_dir[0]) && err && err_sz > 0U) {+ (void)snprintf(err, err_sz, "integration asset install paths are unavailable");+ }+ return false;+ }++ char adjacent[CBM_SZ_4K];+ char ownership[CBM_SZ_4K];+ char ownership_parent[CBM_SZ_4K];+ int adjacent_length =+ snprintf(adjacent, sizeof(adjacent), "%s/%s", install_dir, CBM_INTEGRATIONS_ASSET_NAME);+ if (adjacent_length <= 0 || (size_t)adjacent_length >= sizeof(adjacent) ||+ !cbm_integration_assets_ownership_path(home, ownership, sizeof(ownership))) {+ assets_fill_error(err, err_sz);+ return false;+ }+ (void)snprintf(ownership_parent, sizeof(ownership_parent), "%s", ownership);+ char *slash = strrchr(ownership_parent, '/');+ if (!slash) {+ assets_fill_error(err, err_sz);+ return false;+ }+ *slash = '\0';+ if (!cbm_mkdir_p(install_dir, ASSETS_DIR_PERM) ||+ !cbm_mkdir_p(ownership_parent, ASSETS_DIR_PERM)) {+ if (err && err_sz > 0U) {+ (void)snprintf(err, err_sz, "cannot create directories for the verified %s copies",+ CBM_INTEGRATIONS_ASSET_NAME);+ }+ return false;+ }+ if (!assets_stage_target(adjacent, adjacent_transaction_out, err, err_sz) ||+ !assets_stage_target(ownership, ownership_transaction_out, err, err_sz)) {+ bool owner_closed = assets_transaction_close(ownership_transaction_out);+ bool adjacent_closed = assets_transaction_close(adjacent_transaction_out);+ if ((!owner_closed || !adjacent_closed) && err && err_sz > 0U) {+ (void)snprintf(err, err_sz,+ "cannot clean up a partial integration asset install transaction");+ }+ return false;+ }+ return true;+}++static bool assets_stage_owned_removal(const char *path,+ cbm_activation_transaction_t **transaction_out,+ bool *foreign_preserved_out, char *err, size_t err_sz) {+ cbm_path_info_t info;+ if (cbm_path_info_utf8(path, &info) != 0) {+ return true;+ }+ if (!info.is_regular || info.is_symlink || !cbm_integration_assets_verify_file(path)) {+ if (foreign_preserved_out) {+ *foreign_preserved_out = true;+ }+ return true;+ }+ cbm_activation_transaction_status_t status =+ cbm_activation_transaction_stage_removal(path, transaction_out);+ if (status == CBM_ACTIVATION_TRANSACTION_OK && *transaction_out) {+ /* stage_removal snapshots the exact file identity; commit revalidates+ * it, binding this digest check to the file that will be retained. */+ if (cbm_integration_assets_verify_file(path)) {+ return true;+ }+ if (!assets_transaction_close(transaction_out)) {+ if (err && err_sz > 0U) {+ (void)snprintf(err, err_sz,+ "cannot clean up a changed integration asset removal transaction");+ }+ return false;+ }+ if (foreign_preserved_out) {+ *foreign_preserved_out = true;+ }+ return true;+ }+ if (err && err_sz > 0U) {+ (void)snprintf(err, err_sz, "cannot stage owned integration asset removal for %s: %s", path,+ cbm_activation_transaction_status_message(status));+ }+ (void)assets_transaction_close(transaction_out);+ return false;+}++bool cbm_integration_assets_stage_remove(const char *home, const char *install_dir,+ cbm_activation_transaction_t **adjacent_transaction_out,+ cbm_activation_transaction_t **ownership_transaction_out,+ bool *foreign_preserved_out, char *err, size_t err_sz) {+ if (adjacent_transaction_out) {+ *adjacent_transaction_out = NULL;+ }+ if (ownership_transaction_out) {+ *ownership_transaction_out = NULL;+ }+ if (foreign_preserved_out) {+ *foreign_preserved_out = false;+ }+ if (!home || !home[0] || !install_dir || !install_dir[0] || !adjacent_transaction_out ||+ !ownership_transaction_out) {+ if (err && err_sz > 0U) {+ (void)snprintf(err, err_sz, "integration asset uninstall paths are unavailable");+ }+ return false;+ }+ char adjacent[CBM_SZ_4K];+ char ownership[CBM_SZ_4K];+ int adjacent_length =+ snprintf(adjacent, sizeof(adjacent), "%s/%s", install_dir, CBM_INTEGRATIONS_ASSET_NAME);+ if (adjacent_length <= 0 || (size_t)adjacent_length >= sizeof(adjacent) ||+ !cbm_integration_assets_ownership_path(home, ownership, sizeof(ownership))) {+ if (err && err_sz > 0U) {+ (void)snprintf(err, err_sz, "integration asset uninstall paths are too long");+ }+ return false;+ }+ if (!assets_stage_owned_removal(adjacent, adjacent_transaction_out, foreign_preserved_out, err,+ err_sz) ||+ !assets_stage_owned_removal(ownership, ownership_transaction_out, foreign_preserved_out,+ err, err_sz)) {+ bool owner_closed = assets_transaction_close(ownership_transaction_out);+ bool adjacent_closed = assets_transaction_close(adjacent_transaction_out);+ if ((!owner_closed || !adjacent_closed) && err && err_sz > 0U) {+ (void)snprintf(err, err_sz,+ "cannot clean up a partial integration asset removal transaction");+ }+ return false;+ }+ return true;+}++#ifdef CBM_CLI_ENABLE_TEST_APIbool cbm_integration_assets_install(const char *home, bool dry_run, char *err, size_t err_sz) {if (!home || !home[0] || !cbm_integration_assets_require(home, err, err_sz)) {if (!home || !home[0]) {@@ -342,7 +574,7 @@ bool cbm_integration_assets_install(const char *home, bool dry_run, char *err, s}char stored[CBM_SZ_4K];char parent[CBM_SZ_4K];- if (!assets_stored_copy_path(home, stored, sizeof(stored))) {+ if (!cbm_integration_assets_ownership_path(home, stored, sizeof(stored))) {assets_fill_error(err, err_sz);return false;}@@ -360,28 +592,33 @@ bool cbm_integration_assets_install(const char *home, bool dry_run, char *err, s}return false;}- /* Publish by rename so a concurrent reader never sees a torn copy. */- char temp_path[CBM_SZ_4K];- int written = snprintf(temp_path, sizeof(temp_path), "%s.tmp", stored);- if (written <= 0 || (size_t)written >= sizeof(temp_path)) {- assets_fill_error(err, err_sz);+ cbm_activation_transaction_t *transaction = NULL;+ if (!assets_stage_target(stored, &transaction, err, err_sz)) {return false;}- FILE *file = cbm_fopen(temp_path, "wb");- bool wrote = file && fwrite(g_assets.bytes, 1U, g_assets.length, file) == g_assets.length;- if (file && fclose(file) != 0) {- wrote = false;+ cbm_activation_transaction_status_t status = cbm_integration_assets_commit_install(transaction);+ if (status != CBM_ACTIVATION_TRANSACTION_OK) {+ (void)assets_transaction_close(&transaction);+ if (err && err_sz > 0U) {+ (void)snprintf(err, err_sz, "cannot publish the verified %s copy to %s",+ CBM_INTEGRATIONS_ASSET_NAME, stored);+ }+ return false;}- if (!wrote || cbm_rename_replace(temp_path, stored) != 0) {- (void)cbm_unlink(temp_path);+ status = cbm_activation_transaction_finalize(transaction);+ bool finalized =+ status == CBM_ACTIVATION_TRANSACTION_OK || status == CBM_ACTIVATION_TRANSACTION_DEFERRED;+ bool closed = cbm_activation_transaction_close(&transaction) == CBM_ACTIVATION_TRANSACTION_OK;+ if (!finalized || !closed) {if (err && err_sz > 0U) {- (void)snprintf(err, err_sz, "cannot write the verified %s copy to %s",+ (void)snprintf(err, err_sz, "cannot finalize the verified %s copy at %s",CBM_INTEGRATIONS_ASSET_NAME, stored);}return false;}return true;}+#endifconst cbm_integration_template_t *cbm_integration_template(const char *id) {if (!id || !assets_resolve(NULL)) {diff --git a/src/cli/integration_assets.h b/src/cli/integration_assets.hindex 6fb8748c5..171cd7904 100644--- a/src/cli/integration_assets.h+++ b/src/cli/integration_assets.h@@ -5,8 +5,10 @@* complete shebang'd shell scripts, their PowerShell/.cmd twins, and the* generated JS/TS client modules — as C string literals, written to client* config dirs at 0755. That block of script-shaped bytes inside an unsigned- * executable is exactly the surface AV classifiers score (Wacatac.B!ml), so- * the bodies now live in ONE shipped data file, assets/cbm-integrations.json,+ * executable overlaps script-bearing installer/launcher feature families used+ * by static malware classifiers. That does not identify the cause of any+ * opaque vendor verdict. The unnecessary bodies now live in ONE independently+ * inspectable data file, assets/cbm-integrations.json,* and the binary embeds exactly ONE constant about them: the file's SHA-256* (generated at build time into cbm_integrations_hash.h).*@@ -19,16 +21,18 @@* override fails, it never falls back), else next to the running binary (the* flat release-archive layout install.sh/install.ps1 execute from), else the* source-tree layout <bindir>/../../assets (build/c/ builds and test-runner),- * else the stored copy under <home>/.cbm/assets/<version>/.+ * else the stored copy under <home>/.cbm/assets/<sha256>/.** The stored copy is the OWNERSHIP REFERENCE: `install` persists the verified- * bytes to <home>/.cbm/assets/<version>/ — a SIBLING of the disposable cache+ * bytes to <home>/.cbm/assets/<sha256>/ — a SIBLING of the disposable cache* (~/.cache/codebase-memory-mcp), never inside it — so uninstall can decide* "is this deployed file ours?" by materializing templates from it long after* the release archive is gone. Deciding ownership by materialize-and-compare* against these templates REPLACES the old exact-match against embedded* literals; released[] carries the historical bodies older versions wrote, so- * upgrades and uninstalls keep recognising them. Foreign or user-modified+ * upgrades and uninstalls keep recognising them. Content addressing prevents+ * same-version rebuilds from overwriting another build's ownership reference.+ * Foreign or user-modified* files are preserved exactly as before.** Single-threaded by design: only the CLI install/uninstall paths touch this,@@ -40,6 +44,8 @@#include <stdbool.h>#include <stddef.h>+#include "cli/activation_transaction.h"+#define CBM_INTEGRATIONS_ASSET_NAME "cbm-integrations.json"/* One template body. `text` may contain {{BIN}} / {{EVENT}} / {{TOOLS}} /@@ -69,11 +75,46 @@ typedef struct {* actionable message. */bool cbm_integration_assets_require(const char *home, char *err, size_t err_sz);-/* Install-time step: verify (as above) and persist the verified bytes to- * <home>/.cbm/assets/<version>/cbm-integrations.json. Verification failure or- * an unwritable store is an error — the caller must not partially install.- * dry_run verifies only and writes nothing. */-bool cbm_integration_assets_install(const char *home, bool dry_run, char *err, size_t err_sz);+/* Verify one explicit file against this binary's compiled digest. This does+ * not consult fallbacks or populate the template cache. */+bool cbm_integration_assets_verify_file(const char *path);++/* Content-addressed ownership reference used by install/uninstall. */+bool cbm_integration_assets_ownership_path(const char *home, char *out, size_t out_sz);++/* Stage both runtime copies from the verified immutable snapshot: the fixed+ * sidecar beside the target executable and the content-addressed ownership reference.+ * No target is changed until the caller commits both transactions. The caller+ * must hold the native activation guard from this call through rollback or+ * finalize. A failure closes every partial stage and leaves both outputs NULL. */+bool cbm_integration_assets_stage_install(const char *home, const char *install_dir,+ cbm_activation_transaction_t **adjacent_transaction_out,+ cbm_activation_transaction_t **ownership_transaction_out,+ char *err, size_t err_sz);++/* Publish one staged integration copy and validate the exact post-rename+ * target against this binary's compiled digest before it can be finalized.+ * If the staged inode was rewritten after staging, commit rolls the previous+ * target back and returns VALIDATION_FAILED. */+cbm_activation_transaction_status_t cbm_integration_assets_commit_install(+ cbm_activation_transaction_t *transaction);++/* Stage removal of exact, hash-owned adjacent and ownership copies. Missing+ * files are successful no-ops. Foreign or modified files are preserved and+ * reported through foreign_preserved_out. The caller owns any returned+ * transactions and must commit/rollback/finalize them under the activation+ * guard. */+bool cbm_integration_assets_stage_remove(const char *home, const char *install_dir,+ cbm_activation_transaction_t **adjacent_transaction_out,+ cbm_activation_transaction_t **ownership_transaction_out,+ bool *foreign_preserved_out, char *err, size_t err_sz);++/* Move the snapshotted target to the transaction's private retained path,+ * then hash that exact retained object before permitting final deletion. An+ * in-place rewrite after stage_remove is restored and reported as+ * VALIDATION_FAILED instead of being deleted. */+cbm_activation_transaction_status_t cbm_integration_assets_commit_removal(+ cbm_activation_transaction_t *transaction);/* Template lookup for this platform. Returns NULL when the assets are* unavailable or the id/variant is unknown. The returned pointers stay valid@@ -81,6 +122,10 @@ bool cbm_integration_assets_install(const char *home, bool dry_run, char *err, sconst cbm_integration_template_t *cbm_integration_template(const char *id);#ifdef CBM_CLI_ENABLE_TEST_API+/* Focused lifecycle probe for the ownership-copy publisher. Production uses+ * cbm_integration_assets_stage_install as part of the guarded runtime set. */+bool cbm_integration_assets_install(const char *home, bool dry_run, char *err, size_t err_sz);+/* Drop the cached document so a test can steer resolution via CBM_ASSETS_DIR* (set = authoritative) and observe verification failures deterministically. */void cbm_integration_assets_reset_for_testing(void);diff --git a/src/daemon/application.c b/src/daemon/application.cindex 9062c60cf..7e4a35be7 100644--- a/src/daemon/application.c+++ b/src/daemon/application.c@@ -11,6 +11,8 @@#include "foundation/log.h"#include "foundation/mem.h"#include "foundation/platform.h"+#include "foundation/secure_random.h"+#include "foundation/sha256.h"#include "foundation/subprocess.h"#include "mcp/index_supervisor.h"#include "mcp/mcp.h"@@ -46,6 +48,7 @@ enum {APPLICATION_CONTEXT_HEADER_SIZE = 19,APPLICATION_TOOL_HEADER_SIZE = 5,APPLICATION_UI_CONFIG_REQUEST_SIZE = 7,+ APPLICATION_UI_READINESS_REQUEST_SIZE = 1 + CBM_SHA256_DIGEST_LEN,APPLICATION_PATH_CAP = 4096,APPLICATION_JOB_THREAD_STACK = 256 * 1024,APPLICATION_JOB_POLL_US = 10000,@@ -191,6 +194,8 @@ struct cbm_daemon_application {bool stopping;/* See cbm_daemon_application_set_permanent. */bool permanent;+ uint8_t ui_readiness_secret[CBM_SHA256_DIGEST_LEN];+ bool ui_readiness_secret_set;};static void application_job_unsubscribe_locked(cbm_daemon_application_job_t *job);@@ -2538,6 +2543,24 @@ static cbm_daemon_runtime_application_status_t application_set_ui_config(return saved ? CBM_DAEMON_RUNTIME_APPLICATION_OK : CBM_DAEMON_RUNTIME_APPLICATION_HANDLER_ERROR;}+static cbm_daemon_runtime_application_status_t application_ui_readiness_proof(+ cbm_daemon_application_t *application, const uint8_t *request, uint32_t request_length,+ uint8_t **response_out, uint32_t *response_length_out) {+ if (!application->ui_readiness_secret_set ||+ request_length != APPLICATION_UI_READINESS_REQUEST_SIZE) {+ return CBM_DAEMON_RUNTIME_APPLICATION_REJECTED;+ }+ uint8_t *proof = malloc(CBM_SHA256_DIGEST_LEN);+ if (!proof) {+ return CBM_DAEMON_RUNTIME_APPLICATION_HANDLER_ERROR;+ }+ cbm_hmac_sha256(application->ui_readiness_secret, sizeof(application->ui_readiness_secret),+ request + 1, CBM_SHA256_DIGEST_LEN, proof);+ *response_out = proof;+ *response_length_out = CBM_SHA256_DIGEST_LEN;+ return CBM_DAEMON_RUNTIME_APPLICATION_OK;+}+static cbm_daemon_runtime_application_status_t application_request_dispatch(cbm_daemon_application_t *application, cbm_daemon_application_session_t *session,const uint8_t *request, uint32_t request_length, uint8_t **response_out,@@ -2553,6 +2576,9 @@ static cbm_daemon_runtime_application_status_t application_request_dispatch(response_length_out);case CBM_DAEMON_APPLICATION_REQUEST_SET_UI_CONFIG:return application_set_ui_config(application, session, request, request_length);+ case CBM_DAEMON_APPLICATION_REQUEST_UI_READINESS_PROOF:+ return application_ui_readiness_proof(application, request, request_length, response_out,+ response_length_out);case CBM_DAEMON_APPLICATION_REQUEST_HOOK_AUGMENT: {if (!session->context_set || request_length <= 1) {return CBM_DAEMON_RUNTIME_APPLICATION_REJECTED;@@ -2825,6 +2851,15 @@ cbm_daemon_application_t *cbm_daemon_application_new(application->physical_job_limit = APPLICATION_DEFAULT_PHYSICAL_JOB_LIMIT;size_t aggregate_memory_budget_bytes = cbm_mem_budget();if (config) {+ if ((config->ui_readiness_secret != NULL || config->ui_readiness_secret_length != 0) &&+ (!config->ui_readiness_secret ||+ config->ui_readiness_secret_length != sizeof(application->ui_readiness_secret))) {+ cbm_mutex_destroy(&application->mutex);+ cbm_secure_zero(application->ui_readiness_secret,+ sizeof(application->ui_readiness_secret));+ free(application);+ return NULL;+ }application->watcher = config->watcher;application->config = config->config;application->project_locks = config->project_locks;@@ -2840,6 +2875,12 @@ cbm_daemon_application_t *cbm_daemon_application_new(if (config->update_ops) {application->update_ops = *config->update_ops;}+ if (config->ui_readiness_secret &&+ config->ui_readiness_secret_length == sizeof(application->ui_readiness_secret)) {+ memcpy(application->ui_readiness_secret, config->ui_readiness_secret,+ sizeof(application->ui_readiness_secret));+ application->ui_readiness_secret_set = true;+ }}/* Equal fixed slices keep admission deterministic: starting fewer jobs does* not let an early worker claim memory reserved for later concurrent jobs.@@ -2866,6 +2907,7 @@ cbm_daemon_application_t *cbm_daemon_application_new(if (!application->worker_ops.poll || !application->worker_ops.cancel ||!application->worker_ops.log_path || !application->worker_ops.destroy) {cbm_mutex_destroy(&application->mutex);+ cbm_secure_zero(application->ui_readiness_secret, sizeof(application->ui_readiness_secret));free(application);return NULL;}@@ -2877,6 +2919,7 @@ cbm_daemon_application_t *cbm_daemon_application_new((!application->update_ops.poll || !application->update_ops.cancel ||!application->update_ops.destroy)) {cbm_mutex_destroy(&application->mutex);+ cbm_secure_zero(application->ui_readiness_secret, sizeof(application->ui_readiness_secret));free(application);return NULL;}@@ -3012,6 +3055,7 @@ bool cbm_daemon_application_free_with_timeout(cbm_daemon_application_t *applicatmutations = next;}cbm_mutex_destroy(&application->mutex);+ cbm_secure_zero(application->ui_readiness_secret, sizeof(application->ui_readiness_secret));free(application);return true;}@@ -3178,6 +3222,38 @@ cbm_daemon_runtime_application_status_t cbm_daemon_application_client_set_ui_conreturn status;}+cbm_daemon_runtime_application_status_t cbm_daemon_application_client_ui_readiness_proof(+ cbm_daemon_runtime_client_t *client, const uint8_t challenge[CBM_SHA256_DIGEST_LEN],+ uint8_t proof_out[CBM_SHA256_DIGEST_LEN], uint32_t timeout_ms) {+ if (!client || !challenge || !proof_out) {+ return CBM_DAEMON_RUNTIME_APPLICATION_REJECTED;+ }+ cbm_secure_zero(proof_out, CBM_SHA256_DIGEST_LEN);+ uint8_t *request = malloc(APPLICATION_UI_READINESS_REQUEST_SIZE);+ if (!request) {+ return CBM_DAEMON_RUNTIME_APPLICATION_TRANSPORT_ERROR;+ }+ request[0] = CBM_DAEMON_APPLICATION_REQUEST_UI_READINESS_PROOF;+ memcpy(request + 1, challenge, CBM_SHA256_DIGEST_LEN);+ uint8_t *response = NULL;+ uint32_t response_length = 0;+ cbm_daemon_runtime_application_status_t status =+ application_client_exchange(client, request, APPLICATION_UI_READINESS_REQUEST_SIZE,+ &response, &response_length, timeout_ms);+ if (status == CBM_DAEMON_RUNTIME_APPLICATION_OK) {+ if (!response || response_length != CBM_SHA256_DIGEST_LEN) {+ status = CBM_DAEMON_RUNTIME_APPLICATION_HANDLER_ERROR;+ } else {+ memcpy(proof_out, response, CBM_SHA256_DIGEST_LEN);+ }+ }+ if (response) {+ cbm_secure_zero(response, response_length);+ }+ free(response);+ return status;+}+static cbm_daemon_runtime_application_status_t application_client_text_request_tagged(cbm_daemon_runtime_client_t *client, cbm_daemon_runtime_application_token_t request_token,cbm_daemon_application_request_kind_t kind, const char *text, uint8_t **response_out,diff --git a/src/daemon/application.h b/src/daemon/application.hindex ed35c750b..933186aa7 100644--- a/src/daemon/application.h+++ b/src/daemon/application.h@@ -79,6 +79,11 @@ typedef struct {* process-local manager; the daemon job registry reserves index projects* in-process and must not hold the worker's OS lease. */cbm_project_lock_manager_t *project_locks;+ /* Copied at construction. A production host supplies one fresh 32-byte+ * secret per daemon generation; tests may omit it when readiness is not+ * under test. */+ const uint8_t *ui_readiness_secret;+ size_t ui_readiness_secret_length;} cbm_daemon_application_config_t;typedef enum {@@ -87,6 +92,7 @@ typedef enum {CBM_DAEMON_APPLICATION_REQUEST_TOOL = 3,CBM_DAEMON_APPLICATION_REQUEST_HOOK_AUGMENT = 4,CBM_DAEMON_APPLICATION_REQUEST_SET_UI_CONFIG = 5,+ CBM_DAEMON_APPLICATION_REQUEST_UI_READINESS_PROOF = 6,} cbm_daemon_application_request_kind_t;typedef enum {@@ -132,6 +138,13 @@ cbm_daemon_runtime_application_status_t cbm_daemon_application_client_set_ui_concbm_daemon_runtime_client_t *client, uint8_t update_mask, bool ui_enabled, int ui_port,uint32_t timeout_ms);+/* Ask the authenticated daemon generation to prove possession of its private+ * readiness secret for this caller-supplied challenge. The secret itself never+ * crosses IPC. Both challenge and proof are exactly one SHA-256 digest. */+cbm_daemon_runtime_application_status_t cbm_daemon_application_client_ui_readiness_proof(+ cbm_daemon_runtime_client_t *client, const uint8_t challenge[32], uint8_t proof_out[32],+ uint32_t timeout_ms);+cbm_daemon_runtime_application_status_t cbm_daemon_application_client_mcp(cbm_daemon_runtime_client_t *client, const char *message, uint8_t **response_out,uint32_t *response_length_out, uint32_t timeout_ms);diff --git a/src/daemon/bootstrap.c b/src/daemon/bootstrap.cindex 1fd5d7370..5f1a3e82a 100644--- a/src/daemon/bootstrap.c+++ b/src/daemon/bootstrap.c@@ -159,6 +159,7 @@ cbm_daemon_process_role_t cbm_daemon_process_role(int argc, char *const argv[])}static const char *const stateless_commands[] = {+ "--verify-runtime-assets","install","uninstall","update",diff --git a/src/daemon/host.c b/src/daemon/host.cindex 61dcf14af..c038dc135 100644--- a/src/daemon/host.c+++ b/src/daemon/host.c@@ -16,14 +16,17 @@#include "foundation/log.h"#include "foundation/mem.h"#include "foundation/platform.h"+#include "foundation/secure_random.h"+#include "foundation/sha256.h"#include "mcp/index_supervisor.h"#include "store/store.h"#include "ui/config.h"-#include "ui/embedded_assets.h"+#include "ui/asset_pack.h"#include "ui/http_server.h"#include "watcher/watcher.h"#include <stdbool.h>+#include <stdatomic.h>#include <stdint.h>#include <stdio.h>#include <stdlib.h>@@ -47,6 +50,7 @@ enum {HOST_HTTP_CONFIG_POLL_MS = 1000,HOST_HTTP_RETRY_INITIAL_MS = 1000,HOST_HTTP_RETRY_MAX_MS = 30000,+ HOST_UI_ASSET_SHUTDOWN_MS = 10000,HOST_WATCH_INTERVAL_MS = 5000,HOST_CONFLICT_LOG_CAP = 1024 * 1024,HOST_OPERATION_LOG_CAP = 5 * 1024 * 1024,@@ -85,8 +89,13 @@ struct host_state {cbm_http_server_t *http;cbm_thread_t watcher_thread;cbm_thread_t http_thread;+ cbm_thread_t ui_assets_thread;bool watcher_started;bool http_started;+ bool ui_assets_started;+ bool ui_assets_start_failed;+ bool ui_assets_failure_logged;+ atomic_bool ui_assets_completed;bool http_retiring;bool http_config_loaded;bool http_config_enabled;@@ -97,6 +106,7 @@ struct host_state {uint32_t http_retry_delay_ms;uint32_t http_largest_scheduled_retry_ms;const host_http_ops_t *http_ops;+ uint8_t ui_readiness_secret[CBM_SHA256_DIGEST_LEN];};static FILE *g_host_log_file = NULL;@@ -288,6 +298,18 @@ static void *host_http_thread(void *opaque) {return NULL;}+static void *host_ui_assets_thread(void *opaque) {+ host_state_t *host = opaque;+ char error[HOST_PATH_CAP];+ if (cbm_ui_assets_warm(cbm_get_home_dir(), error, sizeof(error))) {+ cbm_log_info("ui.assets_ready", "pack", CBM_UI_ASSET_PACK_NAME);+ } else if (cbm_ui_assets_state() != CBM_UI_ASSETS_CANCELLED) {+ cbm_log_warn("ui.assets_unavailable", "reason", error);+ }+ atomic_store_explicit(&host->ui_assets_completed, true, memory_order_release);+ return NULL;+}+static int host_watcher_index(const char *project_name, const char *root_path, void *opaque) {host_state_t *host = opaque;return host && host->application@@ -333,6 +355,7 @@ static void host_http_server_configure_default(void *context, cbm_http_server_tcbm_http_server_set_index_executor(server, host_ui_index, host);cbm_http_server_set_project_mutation_guard(server, host_ui_mutation_begin, host_ui_mutation_end,host);+ cbm_http_server_set_readiness_secret(server, host->ui_readiness_secret);}static void host_http_server_stop_default(void *context, cbm_http_server_t *server) {@@ -429,16 +452,31 @@ static void host_http_reconcile_at(host_state_t *host, uint64_t now_ms, bool forif (!host || !host->http_ops) {return;}- if (!force_config_load && host->http_config_loaded && now_ms < host->http_next_config_load_ms) {- return;+ if (host->http_ops == &g_host_http_default_ops) {+ cbm_ui_assets_state_t state = cbm_ui_assets_state();+ host->http_assets_available = state == CBM_UI_ASSETS_READY;+ if ((state == CBM_UI_ASSETS_FAILED || state == CBM_UI_ASSETS_CANCELLED ||+ host->ui_assets_start_failed) &&+ !host->ui_assets_failure_logged) {+ cbm_log_warn("ui.assets_unavailable", "pack", CBM_UI_ASSET_PACK_NAME, "hint",+ "reinstall the matching UI release");+ host->ui_assets_failure_logged = true;+ }+ }+ bool load_config =+ force_config_load || !host->http_config_loaded || now_ms >= host->http_next_config_load_ms;+ cbm_ui_config_t desired = {+ .ui_enabled = host->http_config_enabled,+ .ui_port = host->http_config_port,+ };+ bool config_changed = false;+ if (load_config) {+ host->http_next_config_load_ms = host_deadline_from(now_ms, HOST_HTTP_CONFIG_POLL_MS);+ host->http_ops->config_load(host->http_ops->context, &desired);+ config_changed = !host->http_config_loaded ||+ desired.ui_enabled != host->http_config_enabled ||+ desired.ui_port != host->http_config_port;}- host->http_next_config_load_ms = host_deadline_from(now_ms, HOST_HTTP_CONFIG_POLL_MS);-- cbm_ui_config_t desired;- host->http_ops->config_load(host->http_ops->context, &desired);- bool config_changed = !host->http_config_loaded ||- desired.ui_enabled != host->http_config_enabled ||- desired.ui_port != host->http_config_port;if (config_changed && !host->http_retiring) {host->http_retiring = true;host->http_retry_at_ms = now_ms;@@ -468,10 +506,9 @@ static void host_http_reconcile_at(host_state_t *host, uint64_t now_ms, bool forreturn;}if (!host->http_assets_available) {- if (config_changed) {+ if (config_changed && cbm_ui_assets_state() == CBM_UI_ASSETS_UNAVAILABLE) {cbm_log_warn("ui.no_assets", "hint", "rebuild with: make -f Makefile.cbm cbm-with-ui");}- host->http_retry_at_ms = UINT64_MAX;return;}if (now_ms < host->http_retry_at_ms) {@@ -505,6 +542,9 @@ static void host_background_stop(host_state_t *host) {if (host->watcher) {cbm_watcher_stop(host->watcher);}+ if (host->ui_assets_started) {+ cbm_ui_assets_request_cancel();+ }}static bool host_background_join(host_state_t *host) {@@ -520,6 +560,18 @@ static bool host_background_join(host_state_t *host) {}host->watcher_started = false;}+ if (host->ui_assets_started) {+ uint64_t deadline = host_deadline_from(cbm_now_ms(), HOST_UI_ASSET_SHUTDOWN_MS);+ while (!atomic_load_explicit(&host->ui_assets_completed, memory_order_acquire) &&+ cbm_now_ms() < deadline) {+ cbm_usleep(1000);+ }+ if (!atomic_load_explicit(&host->ui_assets_completed, memory_order_acquire) ||+ cbm_thread_join(&host->ui_assets_thread) != 0) {+ return false;+ }+ host->ui_assets_started = false;+ }return true;}@@ -557,11 +609,17 @@ static void host_state_free(host_state_t *host) {host_cleanup_release_until_complete(host_project_lock_manager_free_once,&host->project_locks, "project_lock_manager_cleanup");}+ cbm_secure_zero(host->ui_readiness_secret, sizeof(host->ui_readiness_secret));}static bool host_state_prepare(host_state_t *host, const cbm_daemon_ipc_endpoint_t *endpoint) {host->http_ops = &g_host_http_default_ops;- host->http_assets_available = CBM_EMBEDDED_FILE_COUNT > 0;+ host->http_assets_available = false;+ atomic_init(&host->ui_assets_completed, false);+ if (!cbm_secure_random(host->ui_readiness_secret, sizeof(host->ui_readiness_secret))) {+ cbm_log_error("daemon.readiness_secret_failed", "reason", "system_rng_unavailable");+ return false;+ }size_t aggregate_memory_budget_bytes = cbm_mem_budget();const char *cache = cbm_resolve_cache_dir();if (!cache || !cache[0]) {@@ -581,6 +639,8 @@ static bool host_state_prepare(host_state_t *host, const cbm_daemon_ipc_endpoint.config = host->runtime_config,.aggregate_memory_budget_bytes = aggregate_memory_budget_bytes,.project_locks = host->project_locks,+ .ui_readiness_secret = host->ui_readiness_secret,+ .ui_readiness_secret_length = sizeof(host->ui_readiness_secret),};host->application = cbm_daemon_application_new(&application_config);if (host->application && host->permanent) {@@ -817,6 +877,18 @@ static bool host_background_start(host_state_t *host) {}host->watcher_started = true;+ /* Runtime publication already succeeded before this function is called.+ * Pack I/O and hashing therefore run concurrently with normal daemon+ * service rather than extending its startup critical path. */+ if (cbm_ui_assets_supported()) {+ if (cbm_thread_create(&host->ui_assets_thread, 0, host_ui_assets_thread, host) == 0) {+ host->ui_assets_started = true;+ } else {+ host->ui_assets_start_failed = true;+ cbm_log_warn("ui.assets_unavailable", "reason", "warmup_thread_create_failed");+ }+ }+host_http_reconcile_at(host, cbm_now_ms(), true);return true;}diff --git a/src/daemon/ipc.c b/src/daemon/ipc.cindex ff8ef1c7d..5b0a76f80 100644--- a/src/daemon/ipc.c+++ b/src/daemon/ipc.c@@ -11,6 +11,7 @@#include "foundation/macos_acl.h"#include "foundation/private_file_lock_internal.h"#include "foundation/sha256.h"+#include "foundation/secure_random.h"#include <errno.h>#include <limits.h>@@ -4644,21 +4645,8 @@ static win_rendezvous_status_t win_endpoint_refresh_rendezvous(return result;}-typedef LONG(WINAPI *bcrypt_gen_random_fn)(void *, unsigned char *, ULONG, ULONG);-static bool win_generation_nonce(uint8_t nonce[CBM_DAEMON_IPC_WINDOWS_NONCE_SIZE]) {- enum { WIN_BCRYPT_USE_SYSTEM_PREFERRED_RNG = 0x00000002 };- HMODULE bcrypt = LoadLibraryW(L"bcrypt.dll");- bcrypt_gen_random_fn generate =- bcrypt ? (bcrypt_gen_random_fn)(void (*)(void))GetProcAddress(bcrypt, "BCryptGenRandom")- : NULL;- LONG status = generate ? generate(NULL, nonce, CBM_DAEMON_IPC_WINDOWS_NONCE_SIZE,- WIN_BCRYPT_USE_SYSTEM_PREFERRED_RNG)- : (LONG)-1;- if (bcrypt) {- (void)FreeLibrary(bcrypt);- }- return status >= 0;+ return cbm_secure_random(nonce, CBM_DAEMON_IPC_WINDOWS_NONCE_SIZE);}static int win_private_lock_probe(cbm_private_lock_directory_t *directory, const char *base_name) {diff --git a/src/daemon/runtime.c b/src/daemon/runtime.cindex 749a7d2b6..1699ebfb5 100644--- a/src/daemon/runtime.c+++ b/src/daemon/runtime.c@@ -711,10 +711,17 @@ static bool runtime_process_image_reference_acquire(LARGE_INTEGER size_before;LARGE_INTEGER size_after;bool ok = runtime_windows_process_image_snapshot(process, &process_before);- HANDLE file = ok ? CreateFileW(process_before.path, GENERIC_READ,- FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING,- FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_SEQUENTIAL_SCAN, NULL)- : INVALID_HANDLE_VALUE;+ /* QueryFullProcessImageNameW returns a stable identity spelling for the+ * before/after comparison, but its Win32/DOS form may exceed MAX_PATH.+ * Keep that snapshot byte-for-byte and use an owned extended spelling only+ * at the file-API boundary. */+ wchar_t *open_path = ok ? cbm_wide_path_to_extended(process_before.path) : NULL;+ HANDLE file = open_path+ ? CreateFileW(open_path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE,+ NULL, OPEN_EXISTING,+ FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_SEQUENTIAL_SCAN, NULL)+ : INVALID_HANDLE_VALUE;+ free(open_path);ok = ok && runtime_windows_file_snapshot(file, &file_before, &size_before) &&(!fingerprint || cbm_daemon_build_fingerprint_native_file((uintptr_t)file, fingerprint)) &&runtime_windows_file_snapshot(file, &file_after, &size_after) &&diff --git a/src/foundation/compat_fs.c b/src/foundation/compat_fs.cindex b14c1abb1..692813c20 100644--- a/src/foundation/compat_fs.c+++ b/src/foundation/compat_fs.c@@ -125,7 +125,7 @@ int cbm_path_info_utf8(const char *path, cbm_path_info_t *out) {if (!path || !out) {return CBM_NOT_FOUND;}- wchar_t *wpath = cbm_utf8_to_wide(path);+ wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {return CBM_NOT_FOUND;}@@ -511,15 +511,28 @@ bool cbm_mkdir_p(const char *path, int mode) {return false;}wmemcpy(tmp, wpath, wlen + 1);- size_t start = wlen > 0U && (tmp[0] == L'/' || tmp[0] == L'\\') ? 1U : 0U;- if (wlen >= 3U && tmp[1] == L':' && (tmp[2] == L'/' || tmp[2] == L'\\')) {+ size_t start = wlen > 0U && cbm_win_path_separator(tmp[0]) ? 1U : 0U;+ if (wlen >= 8U && _wcsnicmp(tmp, L"\\\\?\\UNC\\", 8U) == 0) {+ /* Extended UNC roots are \\?\UNC\server\share\. Neither the server+ * nor share component is creatable; begin with the first descendant. */+ size_t separators = 0U;+ start = 8U;+ while (start < wlen && separators < 2U) {+ if (cbm_win_path_separator(tmp[start])) {+ separators++;+ }+ start++;+ }+ } else if (wlen >= 7U && wcsncmp(tmp, L"\\\\?\\", 4U) == 0 && tmp[5] == L':' &&+ cbm_win_path_separator(tmp[6])) {+ start = 7U;+ } else if (wlen >= 3U && tmp[1] == L':' && cbm_win_path_separator(tmp[2])) {start = 3U;- } else if (wlen >= 2U && (tmp[0] == L'/' || tmp[0] == L'\\') &&- (tmp[1] == L'/' || tmp[1] == L'\\')) {+ } else if (wlen >= 2U && cbm_win_path_separator(tmp[0]) && cbm_win_path_separator(tmp[1])) {size_t separators = 0U;start = 2U;while (start < wlen && separators < 2U) {- if (tmp[start] == L'/' || tmp[start] == L'\\') {+ if (cbm_win_path_separator(tmp[start])) {separators++;}start++;@@ -527,8 +540,8 @@ bool cbm_mkdir_p(const char *path, int mode) {}bool ok = true;for (wchar_t *p = tmp + start; ok && *p; p++) {- if (*p == L'/' || *p == L'\\') {- if (p == tmp || p[-1] == L'/' || p[-1] == L'\\') {+ if (cbm_win_path_separator(*p)) {+ if (p == tmp || cbm_win_path_separator(p[-1])) {continue;}wchar_t separator = *p;@@ -1043,8 +1056,8 @@ int cbm_rename_noreplace(const char *src, const char *dst) {return CBM_NOT_FOUND;}#ifdef _WIN32- wchar_t *wsrc = cbm_utf8_to_wide(src);- wchar_t *wdst = cbm_utf8_to_wide(dst);+ wchar_t *wsrc = cbm_path_to_wide(src);+ wchar_t *wdst = cbm_path_to_wide(dst);int ret = CBM_NOT_FOUND;if (wsrc && wdst) {ret = MoveFileExW(wsrc, wdst, MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)diff --git a/src/foundation/secure_random.c b/src/foundation/secure_random.cnew file mode 100644index 000000000..e5a4f6040--- /dev/null+++ b/src/foundation/secure_random.c@@ -0,0 +1,79 @@+#include "foundation/secure_random.h"++#include <stdint.h>++void cbm_secure_zero(void *buffer, size_t length) {+ volatile uint8_t *cursor = buffer;+ while (cursor && length > 0) {+ *cursor++ = 0;+ length--;+ }+}++#ifdef _WIN32+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#include <windows.h>+#include <bcrypt.h>++bool cbm_secure_random(void *buffer, size_t length) {+ if (!buffer && length != 0) {+ return false;+ }+ uint8_t *cursor = buffer;+ while (length > 0) {+ ULONG chunk = length > UINT32_MAX ? UINT32_MAX : (ULONG)length;+ if (BCryptGenRandom(NULL, cursor, chunk, BCRYPT_USE_SYSTEM_PREFERRED_RNG) < 0) {+ return false;+ }+ cursor += chunk;+ length -= chunk;+ }+ return true;+}++#else++#include <errno.h>+#include <fcntl.h>+#include <unistd.h>++bool cbm_secure_random(void *buffer, size_t length) {+ if (!buffer && length != 0) {+ return false;+ }+ int flags = O_RDONLY;+#ifdef O_CLOEXEC+ flags |= O_CLOEXEC;+#endif+ int fd;+ do {+ fd = open("/dev/urandom", flags);+ } while (fd < 0 && errno == EINTR);+ if (fd < 0) {+ return false;+ }++ uint8_t *cursor = buffer;+ bool ok = true;+ while (length > 0) {+ ssize_t count = read(fd, cursor, length);+ if (count > 0) {+ cursor += (size_t)count;+ length -= (size_t)count;+ } else if (count < 0 && errno == EINTR) {+ continue;+ } else {+ ok = false;+ break;+ }+ }+ /* Do not retry close(2) after EINTR: on platforms that have already+ * released the descriptor, a retry could close an unrelated fd reused by+ * another thread. The random bytes are valid once the read completed. */+ int close_result = close(fd);+ return ok && (close_result == 0 || errno == EINTR);+}++#endifdiff --git a/src/foundation/secure_random.h b/src/foundation/secure_random.hnew file mode 100644index 000000000..dd90b7546--- /dev/null+++ b/src/foundation/secure_random.h@@ -0,0 +1,15 @@+#ifndef CBM_SECURE_RANDOM_H+#define CBM_SECURE_RANDOM_H++#include <stdbool.h>+#include <stddef.h>++/* Fill a caller-owned buffer from the operating system CSPRNG. This is a+ * direct platform API/file operation and never invokes a shell or subprocess. */+bool cbm_secure_random(void *buffer, size_t length);++/* Overwrite sensitive caller-owned storage through volatile writes so the+ * compiler cannot discard the erasure as an unobservable dead store. */+void cbm_secure_zero(void *buffer, size_t length);++#endif /* CBM_SECURE_RANDOM_H */diff --git a/src/foundation/sha256.c b/src/foundation/sha256.cindex e8bc6bca7..937e363e6 100644--- a/src/foundation/sha256.c+++ b/src/foundation/sha256.c@@ -2,6 +2,7 @@* against the NIST test vectors in tests/test_cli.c. */#include "foundation/sha256.h"+#include "foundation/secure_random.h"#include <string.h>@@ -126,4 +127,52 @@ void cbm_sha256_hex(const void *data, size_t len, char out[CBM_SHA256_HEX_LEN +out[i * 2 + 1] = hex[digest[i] & 0x0f];}out[CBM_SHA256_HEX_LEN] = '\0';+ cbm_secure_zero(&c, sizeof(c));+ cbm_secure_zero(digest, sizeof(digest));+}++void cbm_hmac_sha256(const void *key, size_t key_len, const void *data, size_t data_len,+ uint8_t out[CBM_SHA256_DIGEST_LEN]) {+ enum { SHA256_BLOCK_LEN = 64 };+ const uint8_t *key_bytes = (const uint8_t *)key;+ uint8_t normalized_key[CBM_SHA256_DIGEST_LEN];+ uint8_t inner_pad[SHA256_BLOCK_LEN];+ uint8_t outer_pad[SHA256_BLOCK_LEN];+ uint8_t inner_digest[CBM_SHA256_DIGEST_LEN];++ if (key_len > SHA256_BLOCK_LEN) {+ cbm_sha256_ctx key_hash;+ cbm_sha256_init(&key_hash);+ cbm_sha256_update(&key_hash, key, key_len);+ cbm_sha256_final(&key_hash, normalized_key);+ cbm_secure_zero(&key_hash, sizeof(key_hash));+ key_bytes = normalized_key;+ key_len = sizeof(normalized_key);+ }++ memset(inner_pad, 0x36, sizeof(inner_pad));+ memset(outer_pad, 0x5c, sizeof(outer_pad));+ for (size_t i = 0; i < key_len; i++) {+ inner_pad[i] ^= key_bytes[i];+ outer_pad[i] ^= key_bytes[i];+ }++ cbm_sha256_ctx inner;+ cbm_sha256_init(&inner);+ cbm_sha256_update(&inner, inner_pad, sizeof(inner_pad));+ cbm_sha256_update(&inner, data, data_len);+ cbm_sha256_final(&inner, inner_digest);++ cbm_sha256_ctx outer;+ cbm_sha256_init(&outer);+ cbm_sha256_update(&outer, outer_pad, sizeof(outer_pad));+ cbm_sha256_update(&outer, inner_digest, sizeof(inner_digest));+ cbm_sha256_final(&outer, out);++ cbm_secure_zero(&inner, sizeof(inner));+ cbm_secure_zero(&outer, sizeof(outer));+ cbm_secure_zero(normalized_key, sizeof(normalized_key));+ cbm_secure_zero(inner_pad, sizeof(inner_pad));+ cbm_secure_zero(outer_pad, sizeof(outer_pad));+ cbm_secure_zero(inner_digest, sizeof(inner_digest));}diff --git a/src/foundation/sha256.h b/src/foundation/sha256.hindex bdfcb1b73..a34a741d3 100644--- a/src/foundation/sha256.h+++ b/src/foundation/sha256.h@@ -27,4 +27,10 @@ void cbm_sha256_final(cbm_sha256_ctx *c, uint8_t out[CBM_SHA256_DIGEST_LEN]);* CBM_SHA256_HEX_LEN + 1 bytes (hex chars + NUL). */void cbm_sha256_hex(const void *data, size_t len, char out[CBM_SHA256_HEX_LEN + 1]);+/* RFC 2104 HMAC-SHA-256. The output is always CBM_SHA256_DIGEST_LEN bytes.+ * A NULL key/data pointer is accepted only when its corresponding length is+ * zero. */+void cbm_hmac_sha256(const void *key, size_t key_len, const void *data, size_t data_len,+ uint8_t out[CBM_SHA256_DIGEST_LEN]);+#endif /* CBM_SHA256_H */diff --git a/src/foundation/win_utf8.h b/src/foundation/win_utf8.hindex 65f70d4b6..2e187c028 100644--- a/src/foundation/win_utf8.h+++ b/src/foundation/win_utf8.h@@ -14,66 +14,183 @@ static inline wchar_t *cbm_utf8_to_wide(const char *utf8) {if (!utf8) {return NULL;}- int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);+ int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, -1, NULL, 0);if (len <= 0) {return NULL;}wchar_t *w = (wchar_t *)malloc((size_t)len * sizeof(wchar_t));- if (w) {- MultiByteToWideChar(CP_UTF8, 0, utf8, -1, w, len);+ if (!w || MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, -1, w, len) != len) {+ free(w);+ return NULL;}return w;}-/* Path-aware conversion for FILE-SYSTEM paths: absolute drive paths longer- * than the legacy limit are canonicalized (GetFullPathNameW) and given the- * extended-length \\?\ prefix so every Win32 file API accepts them- * regardless of the machine's LongPathsEnabled policy. Never use this for- * non-file strings (command lines, pipe names, registry paths). */-static inline wchar_t *cbm_path_to_wide(const char *utf8_path) {- wchar_t *wide = cbm_utf8_to_wide(utf8_path);+static inline int cbm_win_path_separator(wchar_t value) {+ return value == L'\\' || value == L'/';+}++static inline int cbm_win_path_has_namespace_prefix(const wchar_t *path, size_t length) {+ return length >= 4U && cbm_win_path_separator(path[0]) && cbm_win_path_separator(path[1]) &&+ (path[2] == L'?' || path[2] == L'.') && cbm_win_path_separator(path[3]);+}++static inline void cbm_win_path_normalize_wide_separators(wchar_t *path) {+ if (!path) {+ return;+ }+ for (wchar_t *cursor = path; *cursor; cursor++) {+ if (*cursor == L'/') {+ *cursor = L'\\';+ }+ }+}++/* Return an owned FILE-SYSTEM spelling safe for wide Win32 APIs. Paths+ * approaching the legacy limit are first made absolute (so dot segments keep+ * their ordinary Win32 meaning), then expressed in the extended-length+ * namespace. Both drive and UNC paths are supported, as are already-prefixed+ * paths whose separators were normalized to //?/ by the UTF-8 platform layer.+ * This makes behavior independent of the process manifest and LongPathsEnabled+ * policy. Never use this for non-file strings (command lines, pipe names,+ * registry paths). */+static inline wchar_t *cbm_wide_path_to_extended(const wchar_t *wide_path) {+ if (!wide_path) {+ return NULL;+ }+ size_t input_length = wcslen(wide_path);+ if (input_length >= 32767U) {+ return NULL;+ }+ wchar_t *wide = (wchar_t *)malloc((input_length + 1U) * sizeof(*wide));if (!wide) {return NULL;}+ wmemcpy(wide, wide_path, input_length + 1U);size_t length = wcslen(wide);- int drive_absolute =- length >= 3 &&- ((wide[0] >= L'A' && wide[0] <= L'Z') || (wide[0] >= L'a' && wide[0] <= L'z')) &&- wide[1] == L':' && (wide[2] == L'\\' || wide[2] == L'/');- if (!drive_absolute || length < 240U) {+ if (cbm_win_path_has_namespace_prefix(wide, length)) {+ cbm_win_path_normalize_wide_separators(wide);+ return wide;+ }+ if (length < 240U) {return wide;}+DWORD needed = GetFullPathNameW(wide, 0, NULL, NULL);- wchar_t *prefixed =- needed > 0 ? (wchar_t *)malloc(((size_t)needed + 5U) * sizeof(wchar_t)) : NULL;- if (!prefixed) {- free(wide);+ wchar_t *full = needed > 0U ? (wchar_t *)malloc((size_t)needed * sizeof(wchar_t)) : NULL;+ DWORD copied = full ? GetFullPathNameW(wide, needed, full, NULL) : 0U;+ free(wide);+ if (!full || copied == 0U || copied >= needed) {+ free(full);return NULL;}- wmemcpy(prefixed, L"\\\\?\\", 4);- DWORD copied = GetFullPathNameW(wide, needed, prefixed + 4, NULL);- free(wide);- if (copied == 0 || copied >= needed) {- free(prefixed);+ cbm_win_path_normalize_wide_separators(full);++ int drive_absolute =+ copied >= 3U &&+ ((full[0] >= L'A' && full[0] <= L'Z') || (full[0] >= L'a' && full[0] <= L'z')) &&+ full[1] == L':' && full[2] == L'\\';+ int unc_absolute = copied >= 5U && full[0] == L'\\' && full[1] == L'\\';+ if (!drive_absolute && !unc_absolute) {+ free(full);+ return NULL;+ }++ const wchar_t *prefix = drive_absolute ? L"\\\\?\\" : L"\\\\?\\UNC\\";+ size_t prefix_length = drive_absolute ? 4U : 8U;+ size_t tail_offset = drive_absolute ? 0U : 2U;+ size_t tail_length = (size_t)copied - tail_offset;+ size_t extended_length = prefix_length + tail_length;+ /* The documented extended-length limit includes the terminating NUL. */+ if (extended_length >= 32767U) {+ free(full);+ return NULL;+ }+ wchar_t *prefixed = (wchar_t *)malloc((extended_length + 1U) * sizeof(wchar_t));+ if (!prefixed) {+ free(full);return NULL;}+ wmemcpy(prefixed, prefix, prefix_length);+ wmemcpy(prefixed + prefix_length, full + tail_offset, tail_length + 1U);+ free(full);return prefixed;}+static inline wchar_t *cbm_path_to_wide(const char *utf8_path) {+ wchar_t *wide = cbm_utf8_to_wide(utf8_path);+ wchar_t *extended = cbm_wide_path_to_extended(wide);+ free(wide);+ return extended;+}++/* GetModuleFileNameW can preserve the \\?\ spelling used to launch a process.+ * Internal UTF-8 paths use conventional DOS/UNC spelling and add the prefix+ * only at the Win32 file-API boundary, so remove it before widening callers+ * compose adjacent runtime-asset paths. */+static inline void cbm_module_path_unprefix(wchar_t *wide) {+ if (!wide) {+ return;+ }+ if (_wcsnicmp(wide, L"\\\\?\\UNC\\", 8U) == 0) {+ size_t tail_length = wcslen(wide + 8U);+ wmemmove(wide + 2U, wide + 8U, tail_length + 1U);+ wide[0] = L'\\';+ wide[1] = L'\\';+ } else if (wcsncmp(wide, L"\\\\?\\", 4U) == 0) {+ size_t tail_length = wcslen(wide + 4U);+ wmemmove(wide, wide + 4U, tail_length + 1U);+ }+}+static inline char *cbm_wide_to_utf8(const wchar_t *wide) {if (!wide) {return NULL;}- int len = WideCharToMultiByte(CP_UTF8, 0, wide, -1, NULL, 0, NULL, NULL);+ int len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wide, -1, NULL, 0, NULL, NULL);if (len <= 0) {return NULL;}char *u8 = (char *)malloc((size_t)len);- if (u8) {- WideCharToMultiByte(CP_UTF8, 0, wide, -1, u8, len, NULL, NULL);+ if (!u8 ||+ WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wide, -1, u8, len, NULL, NULL) != len) {+ free(u8);+ return NULL;}return u8;}+/* Resolve the running image without passing through the active ANSI code page.+ * The returned UTF-8 string is heap allocated. Grow dynamically so an+ * extended-length install path is never mistaken for a complete path. */+static inline char *cbm_module_path_utf8(void) {+ DWORD capacity = 512U;+ while (capacity <= 32768U) {+ wchar_t *wide = (wchar_t *)calloc((size_t)capacity, sizeof(*wide));+ if (!wide) {+ return NULL;+ }+ SetLastError(ERROR_SUCCESS);+ DWORD length = GetModuleFileNameW(NULL, wide, capacity);+ if (length > 0U && length < capacity) {+ cbm_module_path_unprefix(wide);+ char *utf8 = cbm_wide_to_utf8(wide);+ free(wide);+ return utf8;+ }+ DWORD error = GetLastError();+ free(wide);+ if (length == 0U || (length < capacity && error != ERROR_INSUFFICIENT_BUFFER) ||+ capacity == 32768U) {+ return NULL;+ }+ capacity *= 2U;+ if (capacity > 32768U) {+ capacity = 32768U;+ }+ }+ return NULL;+}+#endif /* _WIN32 */#endif /* CBM_WIN_UTF8_H */diff --git a/src/main.c b/src/main.cindex 04bbfbc72..9061cf165 100644--- a/src/main.c+++ b/src/main.c@@ -14,6 +14,12 @@* per-account daemon. One-shot CLI tool calls run in an isolated local server* and never create or retain a daemon generation.*/+#ifdef _WIN32+/* winsock2 must precede every project header that can transitively include+ * windows.h, otherwise the legacy winsock declarations conflict. */+#include <winsock2.h>+#include <ws2tcpip.h>+#endif#include "cbm.h"#include "store/store.h" // cbm_alloc_init — bind 3rd-party allocators to mimalloc before any sqlite/git init#include "daemon/application.h"@@ -59,24 +65,30 @@ enum {#include "foundation/mem.h"#include "foundation/profile.h"#include "foundation/sha256.h"+#include "foundation/secure_random.h"#include "foundation/win_utf8.h" /* cbm_wide_to_utf8 — Windows UTF-8 argv (#423/#20); no-op on POSIX */#ifdef _WIN32#include <shellapi.h> /* CommandLineToArgvW — not pulled in by windows.h under WIN32_LEAN_AND_MEAN */#include <io.h>#endif#include "ui/http_server.h"-#include "ui/embedded_assets.h"+#include "ui/asset_pack.h"#include "ui/config.h"#include <yyjson/yyjson.h>#include <errno.h>+#include <limits.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <signal.h>#include <stdatomic.h>#ifndef _WIN32+#include <arpa/inet.h>#include <fcntl.h>+#include <netinet/in.h>+#include <poll.h>+#include <sys/socket.h>#include <sys/stat.h>#include <sys/wait.h>#include <unistd.h>@@ -211,12 +223,10 @@ static void main_project_lock_release_fully(cbm_project_lock_lease_t **lease) {* COMPILED OUT of ordinary builds alongside the watchdog probe above. This one* is benign in isolation (an O_EXCL|O_NOFOLLOW PID file), but it is still* test-only code reachable through a caller-supplied path in a shipped binary,- * and its consumers all build with TEST_SEAMS=1. The two seams smoke genuinely- * needs against real release artifacts (CBM_TEST_CRASH_ON / CBM_TEST_HANG_ON- * fault injection, and CBM_TEST_WINDOWS_USER_PATH_RUN_ID, which is what keeps- * the PATH smoke from touching the real user PATH) deliberately REMAIN: smoke's- * whole value is exercising the artifact we ship, and removing them would trade- * release-artifact coverage for a cosmetic win. */+ * and its consumers all build with TEST_SEAMS=1. The crash/hang injectors in+ * internal/cbm/cbm.c are governed by the same boundary. The narrowly validated+ * Windows PATH smoke redirect remains in release artifacts so artifact tests+ * never mutate the runner's live user PATH. */#ifdef CBM_ENABLE_TEST_SEAMSstatic bool main_test_worker_project_lock_marker(const main_local_cli_mutation_t *mutation) {#ifdef _WIN32@@ -1030,6 +1040,14 @@ static int handle_subcommand(int argc, char **argv, cbm_project_lock_manager_t *}}for (int i = SKIP_ONE; i < argc; i++) {+ if (strcmp(argv[i], "--verify-runtime-assets") == 0) {+ if (i != SKIP_ONE || argc != MAIN_CLI_ARGC) {+ (void)fprintf(+ stderr, "codebase-memory-mcp: --verify-runtime-assets accepts no arguments\n");+ return 2;+ }+ return cbm_cmd_verify_runtime_assets();+ }if (strcmp(argv[i], "--version") == 0) {printf("codebase-memory-mcp %s\n", CBM_VERSION);return 0;@@ -1250,6 +1268,21 @@ static uint64_t main_deadline_after(uint32_t timeout_ms) {return now_ms > UINT64_MAX - timeout_ms ? UINT64_MAX : now_ms + timeout_ms;}+static cbm_daemon_ipc_endpoint_t *main_daemon_endpoint_new(void) {+ const char *runtime_parent = NULL;+#ifdef CBM_ENABLE_TEST_SEAMS+ /* Product daemon coordination is deliberately account-wide. Product-level+ * lifecycle guards need an isolated rendezvous namespace so they cannot+ * attach to or retire a developer's real daemon while exercising exact+ * start/open/stop behavior. The seam is opt-in at compile time and the+ * detached child inherits the same environment value. */+ char seam_runtime_parent[MAIN_PATH_CAP];+ runtime_parent = cbm_safe_getenv("CBM_TEST_DAEMON_RUNTIME_PARENT", seam_runtime_parent,+ sizeof(seam_runtime_parent), NULL);+#endif+ return cbm_daemon_bootstrap_endpoint_new(runtime_parent);+}+static bool main_local_cli_feedback_enabled(int argc, char **argv) {bool requested = false;for (int index = 1; index < argc; index++) {@@ -1671,6 +1704,10 @@ enum {MAIN_DAEMON_CTL_PROBE_TIMEOUT_MS = 3000,MAIN_DAEMON_CTL_STOP_TIMEOUT_MS = 10000,MAIN_DAEMON_CTL_START_TIMEOUT_MS = 30000,+ MAIN_DAEMON_CTL_UI_READY_TIMEOUT_MS = 30000,+ MAIN_DAEMON_CTL_UI_PROBE_TIMEOUT_MS = 250,+ MAIN_DAEMON_CTL_UI_PROBE_INTERVAL_US = 50000,+ MAIN_DAEMON_CTL_UI_RESPONSE_CAP = 4096,};static void main_daemon_ctl_print_clients(const uint32_t *pids, uint8_t count, uint16_t committed) {@@ -1683,14 +1720,333 @@ static void main_daemon_ctl_print_clients(const uint32_t *pids, uint8_t count, u}}-static void main_daemon_ctl_print_ui(void) {- if (CBM_EMBEDDED_FILE_COUNT == 0) {+#ifdef _WIN32+typedef SOCKET main_daemon_ctl_socket_t;+#define MAIN_DAEMON_CTL_BAD_SOCKET INVALID_SOCKET+#define main_daemon_ctl_socket_close closesocket+#else+typedef int main_daemon_ctl_socket_t;+#define MAIN_DAEMON_CTL_BAD_SOCKET (-1)+#define main_daemon_ctl_socket_close close+#endif++#ifdef _WIN32+static bool main_daemon_ctl_socket_runtime_ready(void) {+ /* main is single-threaded along this path. As in the HTTP listener, keep+ * Winsock initialized for the short remaining lifetime of this process. */+ static bool attempted = false;+ static bool ready = false;+ if (!attempted) {+ attempted = true;+ WSADATA winsock;+ ready = WSAStartup(MAKEWORD(2, 2), &winsock) == 0;+ }+ return ready;+}+#endif++static bool main_daemon_ctl_socket_set_nonblocking(main_daemon_ctl_socket_t socket_handle) {+#ifdef _WIN32+ u_long enabled = 1;+ return ioctlsocket(socket_handle, FIONBIO, &enabled) == 0;+#else+ int flags = fcntl(socket_handle, F_GETFL, 0);+ return flags >= 0 && fcntl(socket_handle, F_SETFL, flags | O_NONBLOCK) == 0;+#endif+}++static bool main_daemon_ctl_socket_would_block(void) {+#ifdef _WIN32+ int error = WSAGetLastError();+ return error == WSAEWOULDBLOCK || error == WSAEINPROGRESS || error == WSAEALREADY ||+ error == WSAEINTR;+#else+ return errno == EINPROGRESS || errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR;+#endif+}++/* 1 = requested readiness, 0 = timeout/interruption, -1 = socket error. */+static int main_daemon_ctl_socket_wait(main_daemon_ctl_socket_t socket_handle, bool writing,+ int timeout_ms) {+#ifdef _WIN32+ fd_set ready;+ fd_set errors;+ FD_ZERO(&ready);+ FD_ZERO(&errors);+ FD_SET(socket_handle, &ready);+ FD_SET(socket_handle, &errors);+ struct timeval timeout = {+ .tv_sec = timeout_ms / 1000,+ .tv_usec = (timeout_ms % 1000) * 1000,+ };+ int result = select(0, writing ? NULL : &ready, writing ? &ready : NULL, &errors, &timeout);+ if (result <= 0) {+ return result < 0 ? -1 : 0;+ }+ return FD_ISSET(socket_handle, &errors) ? -1 : 1;+#else+ struct pollfd descriptor = {+ .fd = socket_handle,+ .events = writing ? POLLOUT : POLLIN,+ .revents = 0,+ };+ int result = poll(&descriptor, 1, timeout_ms);+ if (result < 0) {+ return errno == EINTR ? 0 : -1;+ }+ if (result == 0) {+ return 0;+ }+ return (descriptor.revents & descriptor.events) != 0 ? 1 : -1;+#endif+}++static int main_daemon_ctl_socket_remaining_ms(uint64_t deadline_ms) {+ uint64_t now_ms = cbm_now_ms();+ if (now_ms >= deadline_ms) {+ return 0;+ }+ uint64_t remaining = deadline_ms - now_ms;+ return remaining > (uint64_t)INT_MAX ? INT_MAX : (int)remaining;+}++static bool main_daemon_ctl_socket_connected(main_daemon_ctl_socket_t socket_handle, int port,+ uint64_t deadline_ms) {+ struct sockaddr_in address;+ memset(&address, 0, sizeof(address));+ address.sin_family = AF_INET;+ address.sin_port = htons((unsigned short)port);+ address.sin_addr.s_addr = htonl(0x7F000001U);+ if (connect(socket_handle, (const struct sockaddr *)&address, sizeof(address)) == 0) {+ return true;+ }+ if (!main_daemon_ctl_socket_would_block()) {+ return false;+ }+ int remaining = main_daemon_ctl_socket_remaining_ms(deadline_ms);+ if (remaining <= 0 || main_daemon_ctl_socket_wait(socket_handle, true, remaining) != 1) {+ return false;+ }+ int socket_error = 0;+#ifdef _WIN32+ int socket_error_size = (int)sizeof(socket_error);+ return getsockopt(socket_handle, SOL_SOCKET, SO_ERROR, (char *)&socket_error,+ &socket_error_size) == 0 &&+ socket_error == 0;+#else+ socklen_t socket_error_size = sizeof(socket_error);+ return getsockopt(socket_handle, SOL_SOCKET, SO_ERROR, &socket_error, &socket_error_size) ==+ 0 &&+ socket_error == 0;+#endif+}++static int main_daemon_ctl_socket_send(main_daemon_ctl_socket_t socket_handle, const char *data,+ size_t length) {+#ifdef _WIN32+ return send(socket_handle, data, (int)length, 0);+#else+#ifdef MSG_NOSIGNAL+ return (int)send(socket_handle, data, length, MSG_NOSIGNAL);+#else+ return (int)send(socket_handle, data, length, 0);+#endif+#endif+}++static int main_daemon_ctl_socket_receive(main_daemon_ctl_socket_t socket_handle, char *data,+ size_t capacity) {+#ifdef _WIN32+ return recv(socket_handle, data, (int)capacity, 0);+#else+ return (int)recv(socket_handle, data, capacity, 0);+#endif+}++typedef struct {+ char challenge_hex[CBM_SHA256_HEX_LEN + 1U];+ char proof_hex[CBM_SHA256_HEX_LEN + 1U];+} main_daemon_ctl_ui_readiness_t;++static void main_daemon_ctl_hex_encode(const uint8_t bytes[CBM_SHA256_DIGEST_LEN],+ char out[CBM_SHA256_HEX_LEN + 1U]) {+ static const char hex[] = "0123456789abcdef";+ for (size_t i = 0; i < CBM_SHA256_DIGEST_LEN; i++) {+ out[i * 2U] = hex[bytes[i] >> 4];+ out[i * 2U + 1U] = hex[bytes[i] & 0x0fU];+ }+ out[CBM_SHA256_HEX_LEN] = '\0';+}++static bool main_daemon_ctl_ui_readiness_prepare(cbm_daemon_runtime_client_t *client,+ main_daemon_ctl_ui_readiness_t *readiness) {+ uint8_t challenge[CBM_SHA256_DIGEST_LEN] = {0};+ uint8_t proof[CBM_SHA256_DIGEST_LEN] = {0};+ if (!client || !readiness) {+ return false;+ }+ cbm_secure_zero(readiness, sizeof(*readiness));+ bool prepared = cbm_secure_random(challenge, sizeof(challenge)) &&+ cbm_daemon_application_client_ui_readiness_proof(client, challenge, proof,+ MAIN_CONNECT_TIMEOUT_MS) ==+ CBM_DAEMON_RUNTIME_APPLICATION_OK;+ if (prepared) {+ main_daemon_ctl_hex_encode(challenge, readiness->challenge_hex);+ main_daemon_ctl_hex_encode(proof, readiness->proof_hex);+ }+ cbm_secure_zero(challenge, sizeof(challenge));+ cbm_secure_zero(proof, sizeof(proof));+ return prepared;+}++static bool main_daemon_ctl_constant_time_equal(const char *left, const char *right,+ size_t length) {+ unsigned char difference = 0;+ for (size_t index = 0; index < length; index++) {+ difference |= (unsigned char)left[index] ^ (unsigned char)right[index];+ }+ return difference == 0;+}++/* Bind HTTP readiness to the exact daemon generation already authenticated by+ * local IPC. The public challenge is safe to expose; a foreign listener cannot+ * compute the expected HMAC because the generation secret never leaves the+ * daemon's application and HTTP server instances. */+static bool main_daemon_ctl_ui_endpoint_ready(int port,+ const main_daemon_ctl_ui_readiness_t *readiness,+ uint32_t timeout_ms) {+ if (port <= 0 || port >= MAIN_MAX_PORT || !readiness || timeout_ms == 0) {+ return false;+ }+#ifdef _WIN32+ if (!main_daemon_ctl_socket_runtime_ready()) {+ return false;+ }+#endif+ main_daemon_ctl_socket_t socket_handle = socket(AF_INET, SOCK_STREAM, 0);+ if (socket_handle == MAIN_DAEMON_CTL_BAD_SOCKET ||+ !main_daemon_ctl_socket_set_nonblocking(socket_handle)) {+ if (socket_handle != MAIN_DAEMON_CTL_BAD_SOCKET) {+ (void)main_daemon_ctl_socket_close(socket_handle);+ }+ return false;+ }+#if !defined(_WIN32) && defined(SO_NOSIGPIPE)+ int no_sigpipe = 1;+ (void)setsockopt(socket_handle, SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe, sizeof(no_sigpipe));+#endif++ uint64_t deadline_ms = main_deadline_after(timeout_ms);+ bool ready = main_daemon_ctl_socket_connected(socket_handle, port, deadline_ms);+ char request[384];+ int request_length = snprintf(request, sizeof(request),+ "GET /__cbm/ui-readiness?challenge=%s HTTP/1.1\r\n"+ "Host: 127.0.0.1:%d\r\nAccept: text/plain\r\n"+ "Connection: close\r\n\r\n",+ readiness->challenge_hex, port);+ if (request_length <= 0 || request_length >= (int)sizeof(request)) {+ ready = false;+ }+ size_t sent = 0;+ while (ready && sent < (size_t)request_length) {+ int remaining = main_daemon_ctl_socket_remaining_ms(deadline_ms);+ if (remaining <= 0 || main_daemon_ctl_socket_wait(socket_handle, true, remaining) != 1) {+ ready = false;+ break;+ }+ int count = main_daemon_ctl_socket_send(socket_handle, request + sent,+ (size_t)request_length - sent);+ if (count > 0) {+ sent += (size_t)count;+ } else if (count == 0 || !main_daemon_ctl_socket_would_block()) {+ ready = false;+ }+ }++ char response[MAIN_DAEMON_CTL_UI_RESPONSE_CAP] = {0};+ size_t received = 0;+ while (ready && received + 1U < sizeof(response)) {+ int remaining = main_daemon_ctl_socket_remaining_ms(deadline_ms);+ if (remaining <= 0 || main_daemon_ctl_socket_wait(socket_handle, false, remaining) != 1) {+ ready = false;+ break;+ }+ int count = main_daemon_ctl_socket_receive(socket_handle, response + received,+ sizeof(response) - received - 1U);+ if (count > 0) {+ received += (size_t)count;+ response[received] = '\0';+ } else if (count == 0 || !main_daemon_ctl_socket_would_block()) {+ break;+ }+ }+ if (received + 1U >= sizeof(response)) {+ response[sizeof(response) - 1U] = '\0';+ }+ char *body = strstr(response, "\r\n\r\n");+ body = body ? body + 4 : NULL;+ ready = ready && received > 0U && strncmp(response, "HTTP/1.1 200 ", 13) == 0 &&+ strstr(response, "\r\nContent-Type: text/plain; charset=utf-8\r\n") != NULL &&+ strstr(response, "\r\nCache-Control: no-store\r\n") != NULL && body &&+ strlen(body) == CBM_SHA256_HEX_LEN &&+ main_daemon_ctl_constant_time_equal(body, readiness->proof_hex, CBM_SHA256_HEX_LEN);+ (void)main_daemon_ctl_socket_close(socket_handle);+ return ready;+}++static uint32_t main_daemon_ctl_ui_ready_timeout_ms(void) {+#ifdef CBM_ENABLE_TEST_SEAMS+ char timeout_text[32];+ const char *configured = cbm_safe_getenv("CBM_TEST_DAEMON_UI_READY_TIMEOUT_MS", timeout_text,+ sizeof(timeout_text), NULL);+ if (configured) {+ char *end = NULL;+ errno = 0;+ unsigned long parsed = strtoul(configured, &end, 10);+ if (errno == 0 && end && *end == '\0' && parsed >= 50UL &&+ parsed <= MAIN_DAEMON_CTL_UI_READY_TIMEOUT_MS) {+ return (uint32_t)parsed;+ }+ }+#endif+ return MAIN_DAEMON_CTL_UI_READY_TIMEOUT_MS;+}++static bool main_daemon_ctl_wait_for_ui(int port, const main_daemon_ctl_ui_readiness_t *readiness,+ uint32_t timeout_ms) {+ uint64_t deadline_ms = main_deadline_after(timeout_ms);+ for (;;) {+ uint64_t now_ms = cbm_now_ms();+ if (now_ms >= deadline_ms) {+ return false;+ }+ uint64_t remaining = deadline_ms - now_ms;+ uint32_t attempt_ms = remaining > MAIN_DAEMON_CTL_UI_PROBE_TIMEOUT_MS+ ? MAIN_DAEMON_CTL_UI_PROBE_TIMEOUT_MS+ : (uint32_t)remaining;+ if (main_daemon_ctl_ui_endpoint_ready(port, readiness, attempt_ms)) {+ return true;+ }+ if (cbm_now_ms() >= deadline_ms) {+ return false;+ }+ cbm_usleep(MAIN_DAEMON_CTL_UI_PROBE_INTERVAL_US);+ }+}++static int main_daemon_ctl_finish_ui_open(cbm_daemon_runtime_client_t **client_io, int port,+ bool open_browser);++static void main_daemon_ctl_print_ui_configuration(void) {+ if (!cbm_ui_assets_supported()) {return;}cbm_ui_config_t ui_config;cbm_ui_config_load(&ui_config);if (ui_config.ui_enabled) {- printf(" ui: http://127.0.0.1:%d\n", ui_config.ui_port);+ printf(" ui: configured at http://127.0.0.1:%d (readiness not checked; "+ "`daemon start --open` verifies it)\n",+ ui_config.ui_port);} else {printf(" ui: disabled (enable with `daemon start` in a UI build)\n");}@@ -1699,6 +2055,20 @@ static void main_daemon_ctl_print_ui(void) {static void main_daemon_ctl_open_browser(int port) {char url[64];(void)snprintf(url, sizeof(url), "http://127.0.0.1:%d", port);+#ifdef CBM_ENABLE_TEST_SEAMS+ char marker_path[MAIN_PATH_CAP];+ if (cbm_safe_getenv("CBM_TEST_DAEMON_OPEN_MARKER", marker_path, sizeof(marker_path), NULL)) {+ FILE *marker = cbm_fopen(marker_path, "wb");+ bool opened = marker && fwrite(url, 1, strlen(url), marker) == strlen(url);+ if (marker && fclose(marker) != 0) {+ opened = false;+ }+ if (!opened) {+ (void)fprintf(stderr, "hint: could not record the test browser request\n");+ }+ return;+ }+#endif#if defined(_WIN32)/* ShellExecuteW resolves the http protocol association directly — no* command shell interprets the argument. Values > 32 signal success. */@@ -1718,6 +2088,50 @@ static void main_daemon_ctl_open_browser(int port) {}}+static int main_daemon_ctl_finish_ui_open(cbm_daemon_runtime_client_t **client_io, int port,+ bool open_browser) {+ if (!open_browser) {+ printf(" ui: warming asynchronously on configured port %d\n", port);+ return EXIT_SUCCESS;+ }+ main_daemon_ctl_ui_readiness_t readiness = {0};+ cbm_daemon_runtime_client_t *client = client_io ? *client_io : NULL;+ if (!main_daemon_ctl_ui_readiness_prepare(client, &readiness)) {+ (void)fprintf(stderr,+ "error: the active daemon generation could not provide an authenticated "+ "UI readiness proof; browser was not opened\n");+ return EXIT_FAILURE;+ }+ /* The generation-bound proof is self-contained. Do not retain the+ * application client while polling HTTP: the daemon deliberately serves+ * one application connection at a time, so an idle retained client would+ * make `daemon status` and other control probes wait for the whole UI+ * deadline. EOF/disconnect cannot weaken the HMAC proof we already hold. */+ if (client_io && *client_io) {+ cbm_daemon_runtime_client_t *owned_client = *client_io;+ *client_io = NULL;+ (void)cbm_daemon_runtime_client_close(owned_client, MAIN_CLOSE_TIMEOUT_MS);+ }+ uint32_t timeout_ms = main_daemon_ctl_ui_ready_timeout_ms();+ bool ready = main_daemon_ctl_wait_for_ui(port, &readiness, timeout_ms);+ cbm_secure_zero(&readiness, sizeof(readiness));+ if (!ready) {+ (void)fprintf(stderr,+ "error: UI endpoint did not become ready within %u ms; browser was not "+ "opened\n",+ timeout_ms);+ (void)fprintf(stderr,+ "hint: verify matching runtime assets with `codebase-memory-mcp "+ "--verify-runtime-assets`, check the daemon log, and if port %d is in use "+ "retry with --port=N\n",+ port);+ return EXIT_FAILURE;+ }+ printf(" ui: http://127.0.0.1:%d\n", port);+ main_daemon_ctl_open_browser(port);+ return EXIT_SUCCESS;+}+static int main_run_daemon_ctl(int argc, char **argv, const cbm_daemon_ipc_endpoint_t *endpoint,const cbm_daemon_build_identity_t *identity,const char *executable_path) {@@ -1771,7 +2185,7 @@ static int main_run_daemon_ctl(int argc, char **argv, const cbm_daemon_ipc_endpo}main_daemon_ctl_print_clients(status.client_pids, status.client_count,status.committed_clients);- main_daemon_ctl_print_ui();+ main_daemon_ctl_print_ui_configuration();return EXIT_SUCCESS;}@@ -1815,8 +2229,43 @@ static int main_run_daemon_ctl(int argc, char **argv, const cbm_daemon_ipc_endpo"last session; run `daemon stop` first if you want a permanent one\n",(unsigned long)status.daemon_pid);}- main_daemon_ctl_print_ui();- return EXIT_SUCCESS;+ if (!cbm_ui_assets_supported()) {+ if (requested_port > 0 || open_browser) {+ (void)fprintf(stderr, "warning: this binary was built without UI support; "+ "--port/--open have no effect\n");+ }+ return EXIT_SUCCESS;+ }+ cbm_ui_config_t ui_config;+ cbm_ui_config_load(&ui_config);+ if (!ui_config.ui_enabled) {+ (void)fprintf(stderr, "error: UI is disabled for the active daemon; browser was not "+ "opened\n");+ return open_browser ? EXIT_FAILURE : EXIT_SUCCESS;+ }+ if (requested_port > 0 && requested_port != ui_config.ui_port) {+ (void)fprintf(stderr,+ "warning: the active daemon remains configured on port %d; stop it "+ "before starting on --port=%d\n",+ ui_config.ui_port, requested_port);+ }+ cbm_daemon_runtime_client_t *ui_client = NULL;+ cbm_daemon_runtime_connect_result_t connect_result;+ if (open_browser) {+ ui_client = cbm_daemon_runtime_client_connect(endpoint, identity,+ MAIN_CONNECT_TIMEOUT_MS, &connect_result);+ if (!ui_client) {+ (void)fprintf(stderr,+ "error: the active daemon generation could not be authenticated; "+ "browser was not opened\n");+ return EXIT_FAILURE;+ }+ }+ int ui_result = main_daemon_ctl_finish_ui_open(&ui_client, ui_config.ui_port, open_browser);+ if (ui_client) {+ (void)cbm_daemon_runtime_client_close(ui_client, MAIN_CLOSE_TIMEOUT_MS);+ }+ return ui_result;}cbm_daemon_bootstrap_config_t start_config = {@@ -1845,19 +2294,25 @@ static int main_run_daemon_ctl(int argc, char **argv, const cbm_daemon_ipc_endpo/* The committed control connection satisfied the daemon's no-client* startup window; configure the UI before departing. */int ui_port = 0;- if (CBM_EMBEDDED_FILE_COUNT > 0) {+ if (cbm_ui_assets_supported()) {cbm_ui_config_t ui_config;cbm_ui_config_load(&ui_config);ui_port = requested_port > 0 ? requested_port : ui_config.ui_port;uint8_t update_mask = 0x03U; /* enabled + port */- if (cbm_daemon_application_client_set_ui_config(start_result.client, update_mask, true,- ui_port, MAIN_CONNECT_TIMEOUT_MS) !=- CBM_DAEMON_RUNTIME_APPLICATION_OK) {- (void)fprintf(stderr, "warning: the daemon did not accept the UI configuration; "- "check `daemon status` and the daemon log\n");+ bool context_set =+ main_set_client_context(start_result.client, ".", CBM_MCP_TOOL_PROFILE_ALL, NULL, NULL,+ MAIN_CONNECT_TIMEOUT_MS);+ if (!context_set || cbm_daemon_application_client_set_ui_config(+ start_result.client, update_mask, true, ui_port,+ MAIN_CONNECT_TIMEOUT_MS) != CBM_DAEMON_RUNTIME_APPLICATION_OK) {+ (void)fprintf(stderr,+ "error: the daemon did not accept the UI configuration; browser was "+ "not opened\n");+ (void)cbm_daemon_runtime_client_close(start_result.client, MAIN_CLOSE_TIMEOUT_MS);+ return EXIT_FAILURE;}} else if (requested_port > 0 || open_browser) {- (void)fprintf(stderr, "warning: this binary was built without the embedded UI; "+ (void)fprintf(stderr, "warning: this binary was built without UI support; ""--port/--open have no effect\n");}@@ -1871,16 +2326,14 @@ static int main_run_daemon_ctl(int argc, char **argv, const cbm_daemon_ipc_endpo}printf("It survives idle periods and session ends; `codebase-memory-mcp daemon stop` ""retires it.\n");- if (CBM_EMBEDDED_FILE_COUNT > 0) {- printf(" ui: http://127.0.0.1:%d\n", ui_port);- printf(" If this port is unavailable the daemon keeps retrying and logs the "- "conflict; pass --port=N for a different port.\n");- if (open_browser) {- main_daemon_ctl_open_browser(ui_port);- }- }- (void)cbm_daemon_runtime_client_close(start_result.client, MAIN_CLOSE_TIMEOUT_MS);- return EXIT_SUCCESS;+ int ui_result =+ cbm_ui_assets_supported()+ ? main_daemon_ctl_finish_ui_open(&start_result.client, ui_port, open_browser)+ : EXIT_SUCCESS;+ if (start_result.client) {+ (void)cbm_daemon_runtime_client_close(start_result.client, MAIN_CLOSE_TIMEOUT_MS);+ }+ return ui_result;}int main(int argc, char **argv) {@@ -2237,7 +2690,7 @@ int main(int argc, char **argv) {return result;}- cbm_daemon_ipc_endpoint_t *endpoint = cbm_daemon_bootstrap_endpoint_new(NULL);+ cbm_daemon_ipc_endpoint_t *endpoint = main_daemon_endpoint_new();if (!endpoint) {(void)fprintf(stderr, "codebase-memory-mcp: secure daemon endpoint could not be created\n");return EXIT_FAILURE;@@ -2389,9 +2842,9 @@ int main(int argc, char **argv) {(void)main_version_cohort_close(&client_cohort_lease, &client_cohort_manager);return EXIT_FAILURE;}- if (explicitly_enabled && CBM_EMBEDDED_FILE_COUNT == 0) {+ if (explicitly_enabled && !cbm_ui_assets_supported()) {(void)fprintf(stderr, "codebase-memory-mcp: --ui requested, but this binary was built "- "without the embedded UI; rebuild with `make -f Makefile.cbm "+ "without UI support; rebuild with `make -f Makefile.cbm ""cbm-with-ui`.\n");}}diff --git a/src/pipeline/pass_calls.c b/src/pipeline/pass_calls.cindex 7eafdda1c..941a3ee56 100644--- a/src/pipeline/pass_calls.c+++ b/src/pipeline/pass_calls.c@@ -967,5 +967,6 @@ void cbm_pipeline_pass_fastapi_depends(cbm_pipeline_ctx_t *ctx, const cbm_file_i}}-/* DLL resolve tracking removed — triggered Windows Defender false positive.- * See issue #89. */+/* DLL resolve tracking remains removed after associated builds received a+ * Windows Defender verdict. The verdict did not provide feature attribution;+ * see issue #89 for the historical observation. */diff --git a/src/ui/asset_manifest_stub.c b/src/ui/asset_manifest_stub.cnew file mode 100644index 000000000..68ed4fb83--- /dev/null+++ b/src/ui/asset_manifest_stub.c@@ -0,0 +1,6 @@+/* Test runners exercise the real loader with no compiled-in pack by default. */+#include <stdint.h>++const char CBM_UI_ASSET_PACK_NAME[] = "";+const char CBM_UI_ASSET_SHA256[] = "";+const uint64_t CBM_UI_ASSET_SIZE = UINT64_C(0);diff --git a/src/ui/asset_pack.c b/src/ui/asset_pack.cnew file mode 100644index 000000000..2629c8474--- /dev/null+++ b/src/ui/asset_pack.c@@ -0,0 +1,892 @@+/* asset_pack.c — Hash-bound loader for the external UI frontend pack. */+#include "ui/asset_pack.h"++#include "foundation/compat.h"+#include "foundation/compat_fs.h"+#include "foundation/constants.h"+#include "foundation/platform.h"+#include "foundation/sha256.h"+#ifdef _WIN32+#include "foundation/win_utf8.h"+#endif++#include <errno.h>+#include <stdatomic.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#ifdef _WIN32+#include <windows.h>+#else+#include <fcntl.h>+#include <sys/stat.h>+#include <unistd.h>+#endif++enum {+ UI_PACK_HEADER_BYTES = 80,+ UI_PACK_ENTRY_BYTES = 24,+ UI_PACK_VERSION = 1,+ UI_PACK_MAX_FILES = 1024,+ UI_PACK_MAX_PATH_BYTES = 255,+ UI_ASSETS_DIR_PERM = 0755,+ UI_ASSET_FILE_PERM = 0644,+ UI_PATH_CAP = 4096,+};++#define UI_PACK_MAX_BYTES ((size_t)CBM_SZ_64K * CBM_SZ_1K)++typedef struct {+ unsigned char *bytes;+ size_t length;+ cbm_ui_asset_t *assets;+ size_t asset_count;+ char *paths;+} ui_asset_snapshot_t;++static ui_asset_snapshot_t g_snapshot;+static atomic_int g_state = CBM_UI_ASSETS_COLD;+static atomic_bool g_cancel_requested = false;+static char g_binary_path[UI_PATH_CAP];++#ifdef CBM_CLI_ENABLE_TEST_API+static bool g_test_manifest_set;+static char g_test_pack_name[UI_PATH_CAP];+static char g_test_sha256[CBM_SHA256_HEX_LEN + 1U];+static uint64_t g_test_size;+#endif++static const char *ui_manifest_name(void) {+#ifdef CBM_CLI_ENABLE_TEST_API+ if (g_test_manifest_set) {+ return g_test_pack_name;+ }+#endif+ return CBM_UI_ASSET_PACK_NAME;+}++static const char *ui_manifest_sha256(void) {+#ifdef CBM_CLI_ENABLE_TEST_API+ if (g_test_manifest_set) {+ return g_test_sha256;+ }+#endif+ return CBM_UI_ASSET_SHA256;+}++static uint64_t ui_manifest_size(void) {+#ifdef CBM_CLI_ENABLE_TEST_API+ if (g_test_manifest_set) {+ return g_test_size;+ }+#endif+ return CBM_UI_ASSET_SIZE;+}++static bool ui_hex_sha256(const char *value) {+ if (!value || strlen(value) != CBM_SHA256_HEX_LEN) {+ return false;+ }+ for (size_t index = 0; index < CBM_SHA256_HEX_LEN; index++) {+ char byte = value[index];+ if (!((byte >= '0' && byte <= '9') || (byte >= 'a' && byte <= 'f'))) {+ return false;+ }+ }+ return true;+}++static bool ui_content_addressed_name(const char *name, const char *sha256) {+ static const char prefix[] = "cbm-ui-";+ static const char suffix[] = ".pack";+ if (!name || !sha256 || strncmp(name, prefix, sizeof(prefix) - 1U) != 0) {+ return false;+ }+ size_t expected_length = (sizeof(prefix) - 1U) + CBM_SHA256_HEX_LEN + (sizeof(suffix) - 1U);+ return strlen(name) == expected_length &&+ strncmp(name + sizeof(prefix) - 1U, sha256, CBM_SHA256_HEX_LEN) == 0 &&+ strcmp(name + expected_length - (sizeof(suffix) - 1U), suffix) == 0;+}++bool cbm_ui_assets_supported(void) {+ const char *name = ui_manifest_name();+ const char *sha256 = ui_manifest_sha256();+ uint64_t size = ui_manifest_size();+ return size >= UI_PACK_HEADER_BYTES && size <= UI_PACK_MAX_BYTES && ui_hex_sha256(sha256) &&+ ui_content_addressed_name(name, sha256);+}++const char *cbm_ui_assets_current_pack_name(void) {+ return cbm_ui_assets_supported() ? ui_manifest_name() : NULL;+}++void cbm_ui_assets_set_binary_path(const char *path) {+ if (!path) {+ g_binary_path[0] = '\0';+ return;+ }+ int written = snprintf(g_binary_path, sizeof(g_binary_path), "%s", path);+ if (written <= 0 || (size_t)written >= sizeof(g_binary_path)) {+ g_binary_path[0] = '\0';+ }+}++static void ui_fill_error(char *err, size_t err_sz, const char *detail) {+ if (!err || err_sz == 0U) {+ return;+ }+ (void)snprintf(err, err_sz,+ "UI assets missing or modified - reinstall the matching release "+ "(expected %s%s%s)",+ ui_manifest_name(), detail && detail[0] ? ": " : "", detail ? detail : "");+}++static uint16_t ui_read_u16(const unsigned char *bytes) {+ return (uint16_t)bytes[0] | ((uint16_t)bytes[1] << 8U);+}++static uint32_t ui_read_u32(const unsigned char *bytes) {+ return (uint32_t)bytes[0] | ((uint32_t)bytes[1] << 8U) | ((uint32_t)bytes[2] << 16U) |+ ((uint32_t)bytes[3] << 24U);+}++static uint64_t ui_read_u64(const unsigned char *bytes) {+ uint64_t value = 0U;+ for (size_t index = 0U; index < sizeof(uint64_t); index++) {+ value |= (uint64_t)bytes[index] << (index * 8U);+ }+ return value;+}++static const char *ui_mime_type(unsigned int mime_id) {+ static const char *const types[] = {+ NULL,+ "text/html; charset=utf-8",+ "application/javascript; charset=utf-8",+ "text/css; charset=utf-8",+ "application/json; charset=utf-8",+ "image/svg+xml",+ "image/png",+ "image/jpeg",+ "image/webp",+ "image/avif",+ "image/x-icon",+ "font/woff2",+ "font/woff",+ "application/wasm",+ };+ return mime_id < sizeof(types) / sizeof(types[0]) ? types[mime_id] : NULL;+}++static unsigned int ui_expected_mime(const char *path) {+ const char *dot = strrchr(path, '.');+ if (!dot) {+ return 0U;+ }+ if (strcmp(dot, ".html") == 0)+ return 1U;+ if (strcmp(dot, ".js") == 0 || strcmp(dot, ".mjs") == 0)+ return 2U;+ if (strcmp(dot, ".css") == 0)+ return 3U;+ if (strcmp(dot, ".json") == 0)+ return 4U;+ if (strcmp(dot, ".svg") == 0)+ return 5U;+ if (strcmp(dot, ".png") == 0)+ return 6U;+ if (strcmp(dot, ".jpg") == 0 || strcmp(dot, ".jpeg") == 0)+ return 7U;+ if (strcmp(dot, ".webp") == 0)+ return 8U;+ if (strcmp(dot, ".avif") == 0)+ return 9U;+ if (strcmp(dot, ".ico") == 0)+ return 10U;+ if (strcmp(dot, ".woff2") == 0)+ return 11U;+ if (strcmp(dot, ".woff") == 0)+ return 12U;+ if (strcmp(dot, ".wasm") == 0)+ return 13U;+ return 0U;+}++static bool ui_path_valid(const unsigned char *path, size_t length) {+ if (length < 2U || length > UI_PACK_MAX_PATH_BYTES || path[0] != '/' ||+ path[length - 1U] == '/') {+ return false;+ }+ for (size_t index = 0U; index < length; index++) {+ unsigned char byte = path[index];+ bool allowed = (byte >= 'A' && byte <= 'Z') || (byte >= 'a' && byte <= 'z') ||+ (byte >= '0' && byte <= '9') || byte == '.' || byte == '_' || byte == '-' ||+ byte == '/';+ if (!allowed || (byte == '/' && index + 1U < length && path[index + 1U] == '/')) {+ return false;+ }+ }+ for (size_t start = 1U; start < length;) {+ size_t end = start;+ while (end < length && path[end] != '/') {+ end++;+ }+ size_t segment = end - start;+ if ((segment == 1U && path[start] == '.') ||+ (segment == 2U && path[start] == '.' && path[start + 1U] == '.')) {+ return false;+ }+ start = end + 1U;+ }+ static const unsigned char index_path[] = "/index.html";+ static const unsigned char asset_prefix[] = "/assets/";+ return (length == sizeof(index_path) - 1U &&+ memcmp(path, index_path, sizeof(index_path) - 1U) == 0) ||+ (length > sizeof(asset_prefix) - 1U &&+ memcmp(path, asset_prefix, sizeof(asset_prefix) - 1U) == 0);+}++static int ui_path_compare(const unsigned char *left, size_t left_length,+ const unsigned char *right, size_t right_length) {+ size_t common = left_length < right_length ? left_length : right_length;+ int compared = memcmp(left, right, common);+ if (compared != 0) {+ return compared;+ }+ return left_length < right_length ? -1 : left_length > right_length ? 1 : 0;+}++static void ui_snapshot_free(ui_asset_snapshot_t *snapshot) {+ if (!snapshot) {+ return;+ }+ free(snapshot->paths);+ free(snapshot->assets);+ free(snapshot->bytes);+ memset(snapshot, 0, sizeof(*snapshot));+}++static bool ui_parse_pack(unsigned char *bytes, size_t length, ui_asset_snapshot_t *out) {+ /* Keep the seven format bytes as separate comparisons. A contiguous+ * native-binary copy would make the composition gate unable to+ * distinguish this parser constant from an accidentally embedded pack. */+ bool valid_magic = bytes && length >= 8U && bytes[0] == 'C' && bytes[1] == 'B' &&+ bytes[2] == 'M' && bytes[3] == 'U' && bytes[4] == 'I' && bytes[5] == 'P' &&+ bytes[6] == 'K' && bytes[7] == 0U;+ if (!bytes || !out || length < UI_PACK_HEADER_BYTES || !valid_magic ||+ ui_read_u16(bytes + 8U) != UI_PACK_VERSION ||+ ui_read_u16(bytes + 10U) != UI_PACK_HEADER_BYTES || ui_read_u32(bytes + 12U) != 0U) {+ return false;+ }+ uint32_t file_count = ui_read_u32(bytes + 16U);+ uint32_t entry_bytes = ui_read_u32(bytes + 20U);+ uint64_t index_offset = ui_read_u64(bytes + 24U);+ uint64_t index_bytes = ui_read_u64(bytes + 32U);+ uint64_t paths_offset = ui_read_u64(bytes + 40U);+ uint64_t paths_bytes = ui_read_u64(bytes + 48U);+ uint64_t payload_offset = ui_read_u64(bytes + 56U);+ uint64_t payload_bytes = ui_read_u64(bytes + 64U);+ uint64_t total_bytes = ui_read_u64(bytes + 72U);+ uint64_t length_u64 = (uint64_t)length;+ if (file_count == 0U || file_count > UI_PACK_MAX_FILES || entry_bytes != UI_PACK_ENTRY_BYTES ||+ index_offset != UI_PACK_HEADER_BYTES ||+ index_bytes != (uint64_t)file_count * UI_PACK_ENTRY_BYTES || index_offset > length_u64 ||+ index_bytes > length_u64 - index_offset || paths_offset != index_offset + index_bytes ||+ paths_offset > length_u64 || paths_bytes > length_u64 - paths_offset ||+ payload_offset != paths_offset + paths_bytes || payload_offset > length_u64 ||+ payload_bytes > length_u64 - payload_offset ||+ total_bytes != payload_offset + payload_bytes || total_bytes != length_u64 ||+ paths_bytes > SIZE_MAX - file_count || payload_bytes > SIZE_MAX) {+ return false;+ }+ cbm_ui_asset_t *assets = calloc(file_count, sizeof(*assets));+ char *paths = malloc((size_t)paths_bytes + file_count);+ if (!assets || !paths) {+ free(assets);+ free(paths);+ return false;+ }+ uint64_t expected_path_offset = 0U;+ uint64_t expected_data_offset = 0U;+ size_t path_storage_offset = 0U;+ bool has_index = false;+ const unsigned char *previous_path = NULL;+ size_t previous_length = 0U;+ for (uint32_t index = 0U; index < file_count; index++) {+ const unsigned char *entry =+ bytes + (size_t)index_offset + (size_t)index * UI_PACK_ENTRY_BYTES;+ uint32_t path_offset = ui_read_u32(entry);+ uint16_t path_length = ui_read_u16(entry + 4U);+ unsigned int mime_id = entry[6U];+ unsigned int cache_id = entry[7U];+ uint64_t data_offset = ui_read_u64(entry + 8U);+ uint64_t data_length = ui_read_u64(entry + 16U);+ if (path_offset != expected_path_offset || path_length == 0U ||+ (uint64_t)path_length > paths_bytes - expected_path_offset ||+ data_offset != expected_data_offset || data_length == 0U ||+ data_length > payload_bytes - expected_data_offset) {+ free(assets);+ free(paths);+ return false;+ }+ const unsigned char *path_bytes = bytes + (size_t)paths_offset + path_offset;+ if (!ui_path_valid(path_bytes, path_length) ||+ (previous_path &&+ ui_path_compare(previous_path, previous_length, path_bytes, path_length) >= 0)) {+ free(assets);+ free(paths);+ return false;+ }+ char *stored_path = paths + path_storage_offset;+ memcpy(stored_path, path_bytes, path_length);+ stored_path[path_length] = '\0';+ const char *mime = ui_mime_type(mime_id);+ bool index_asset = strcmp(stored_path, "/index.html") == 0;+ if (!mime || ui_expected_mime(stored_path) != mime_id ||+ (index_asset ? cache_id != CBM_UI_ASSET_REVALIDATE+ : cache_id != CBM_UI_ASSET_IMMUTABLE) ||+ (index_asset && has_index)) {+ free(assets);+ free(paths);+ return false;+ }+ has_index = has_index || index_asset;+ assets[index] = (cbm_ui_asset_t){+ .path = stored_path,+ .data = bytes + (size_t)payload_offset + (size_t)data_offset,+ .size = (size_t)data_length,+ .content_type = mime,+ .cache = (cbm_ui_asset_cache_t)cache_id,+ };+ previous_path = path_bytes;+ previous_length = path_length;+ expected_path_offset += path_length;+ expected_data_offset += data_length;+ path_storage_offset += path_length + 1U;+ }+ if (!has_index || expected_path_offset != paths_bytes ||+ expected_data_offset != payload_bytes) {+ free(assets);+ free(paths);+ return false;+ }+ *out = (ui_asset_snapshot_t){+ .bytes = bytes,+ .length = length,+ .assets = assets,+ .asset_count = file_count,+ .paths = paths,+ };+ return true;+}++static bool ui_read_regular_file(const char *path, unsigned char **bytes_out, size_t *length_out) {+ *bytes_out = NULL;+ *length_out = 0U;+ cbm_path_info_t info;+ uint64_t expected = ui_manifest_size();+ if (!path || cbm_path_info_utf8(path, &info) != 0 || !info.is_regular || info.is_symlink ||+ info.size <= 0 || (uint64_t)info.size != expected || expected > UI_PACK_MAX_BYTES) {+ return false;+ }+ unsigned char *bytes = malloc((size_t)expected);+ if (!bytes) {+ return false;+ }+#ifdef _WIN32+ wchar_t *wide = cbm_path_to_wide(path);+ HANDLE file = wide ? CreateFileW(wide, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL,+ OPEN_EXISTING,+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, NULL)+ : INVALID_HANDLE_VALUE;+ free(wide);+ if (file == INVALID_HANDLE_VALUE) {+ free(bytes);+ return false;+ }+ BY_HANDLE_FILE_INFORMATION handle_info;+ bool handle_info_ok = GetFileInformationByHandle(file, &handle_info) != 0;+ uint64_t handle_size = handle_info_ok ? ((uint64_t)handle_info.nFileSizeHigh << 32U) |+ (uint64_t)handle_info.nFileSizeLow+ : UINT64_MAX;+ bool ok = handle_info_ok && handle_size == expected &&+ !(handle_info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&+ !(handle_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);+ size_t offset = 0U;+ while (ok && offset < (size_t)expected &&+ !atomic_load_explicit(&g_cancel_requested, memory_order_acquire)) {+ DWORD chunk =+ (DWORD)(((size_t)expected - offset) > CBM_SZ_64K ? CBM_SZ_64K+ : ((size_t)expected - offset));+ DWORD got = 0U;+ ok = ReadFile(file, bytes + offset, chunk, &got, NULL) && got == chunk;+ offset += got;+ }+ (void)CloseHandle(file);+ ok = ok && offset == (size_t)expected;+#else+ int flags = O_RDONLY;+#ifdef O_CLOEXEC+ flags |= O_CLOEXEC;+#endif+#ifdef O_NOFOLLOW+ flags |= O_NOFOLLOW;+#endif+ int file = open(path, flags);+ struct stat opened_info;+ bool ok = file >= 0 && fstat(file, &opened_info) == 0 && S_ISREG(opened_info.st_mode) &&+ (uint64_t)opened_info.st_size == expected;+ size_t offset = 0U;+ while (ok && offset < (size_t)expected &&+ !atomic_load_explicit(&g_cancel_requested, memory_order_acquire)) {+ size_t chunk = (size_t)expected - offset;+ if (chunk > CBM_SZ_64K) {+ chunk = CBM_SZ_64K;+ }+ ssize_t got = read(file, bytes + offset, chunk);+ if (got < 0 && errno == EINTR) {+ continue;+ }+ if (got <= 0) {+ ok = false;+ break;+ }+ offset += (size_t)got;+ }+ if (file >= 0) {+ (void)close(file);+ }+ ok = ok && offset == (size_t)expected;+#endif+ if (!ok || atomic_load_explicit(&g_cancel_requested, memory_order_acquire)) {+ free(bytes);+ return false;+ }+ *bytes_out = bytes;+ *length_out = (size_t)expected;+ return true;+}++static bool ui_verify_bytes(const unsigned char *bytes, size_t length) {+ cbm_sha256_ctx hash;+ cbm_sha256_init(&hash);+ for (size_t offset = 0U; offset < length; offset += CBM_SZ_64K) {+ if (atomic_load_explicit(&g_cancel_requested, memory_order_acquire)) {+ return false;+ }+ size_t chunk = length - offset;+ if (chunk > CBM_SZ_64K) {+ chunk = CBM_SZ_64K;+ }+ cbm_sha256_update(&hash, bytes + offset, chunk);+ }+ uint8_t digest[CBM_SHA256_DIGEST_LEN];+ cbm_sha256_final(&hash, digest);+ static const char hex_chars[] = "0123456789abcdef";+ char hex[CBM_SHA256_HEX_LEN + 1U];+ for (size_t index = 0U; index < sizeof(digest); index++) {+ hex[index * 2U] = hex_chars[digest[index] >> 4U];+ hex[index * 2U + 1U] = hex_chars[digest[index] & 0x0fU];+ }+ hex[CBM_SHA256_HEX_LEN] = '\0';+ return strcmp(hex, ui_manifest_sha256()) == 0;+}++static bool ui_candidate_path(const char *directory, char out[UI_PATH_CAP]) {+ if (!directory || !directory[0]) {+ return false;+ }+ int written = snprintf(out, UI_PATH_CAP, "%s/%s", directory, ui_manifest_name());+ return written > 0 && written < UI_PATH_CAP;+}++static bool ui_binary_directory(char out[UI_PATH_CAP]) {+ int written = snprintf(out, UI_PATH_CAP, "%s", g_binary_path);+ if (written <= 0 || written >= UI_PATH_CAP) {+ return false;+ }+ char *slash = strrchr(out, '/');+#ifdef _WIN32+ char *backslash = strrchr(out, '\\');+ if (backslash && (!slash || backslash > slash)) {+ slash = backslash;+ }+#endif+ if (!slash || slash == out) {+ return false;+ }+ *slash = '\0';+ return true;+}++static bool ui_try_path(const char *path, ui_asset_snapshot_t *snapshot) {+ unsigned char *bytes = NULL;+ size_t length = 0U;+ if (!ui_read_regular_file(path, &bytes, &length)) {+ return false;+ }+ if (!ui_verify_bytes(bytes, length) || !ui_parse_pack(bytes, length, snapshot)) {+ free(bytes);+ return false;+ }+ return true;+}++bool cbm_ui_assets_verify_file(const char *path) {+ if (!cbm_ui_assets_supported() || !path || !path[0]) {+ return false;+ }+ ui_asset_snapshot_t verified = {0};+ bool ok = ui_try_path(path, &verified);+ ui_snapshot_free(&verified);+ return ok;+}++static bool ui_resolve_snapshot(const char *home, ui_asset_snapshot_t *snapshot) {+ static const char missing[] = "\x1f"+ "CBM_UI_ASSETS_DIR_MISSING"+ "\x1f";+ char env_buffer[UI_PATH_CAP];+ char candidate[UI_PATH_CAP];+ const char *override =+ cbm_safe_getenv("CBM_UI_ASSETS_DIR", env_buffer, sizeof(env_buffer), missing);+ if (!override) {+ return false;+ }+ if (strcmp(override, missing) != 0 && override[0]) {+ return ui_candidate_path(override, candidate) && ui_try_path(candidate, snapshot);+ }+ char binary_directory[UI_PATH_CAP];+ if (ui_binary_directory(binary_directory)) {+ if (ui_candidate_path(binary_directory, candidate)) {+ cbm_path_info_t info;+ if (cbm_path_info_utf8(candidate, &info) == 0) {+ return ui_try_path(candidate, snapshot);+ }+ }+ int written = snprintf(candidate, sizeof(candidate), "%s/../share/codebase-memory-mcp/%s",+ binary_directory, ui_manifest_name());+ if (written > 0 && (size_t)written < sizeof(candidate)) {+ cbm_path_info_t info;+ if (cbm_path_info_utf8(candidate, &info) == 0) {+ return ui_try_path(candidate, snapshot);+ }+ }+ }+ (void)home;+ return false;+}++bool cbm_ui_assets_warm(const char *home, char *err, size_t err_sz) {+ if (!cbm_ui_assets_supported()) {+ return true;+ }+ int expected = CBM_UI_ASSETS_COLD;+ if (!atomic_compare_exchange_strong_explicit(&g_state, &expected, CBM_UI_ASSETS_LOADING,+ memory_order_acq_rel, memory_order_acquire)) {+ if (expected == CBM_UI_ASSETS_READY) {+ return true;+ }+ const char *detail = expected == CBM_UI_ASSETS_LOADING ? "load already in progress"+ : expected == CBM_UI_ASSETS_CANCELLED ? "load cancelled"+ : "load previously failed";+ ui_fill_error(err, err_sz, detail);+ return false;+ }+ ui_asset_snapshot_t snapshot = {0};+ bool loaded = ui_resolve_snapshot(home, &snapshot);+ if (atomic_load_explicit(&g_cancel_requested, memory_order_acquire)) {+ ui_snapshot_free(&snapshot);+ atomic_store_explicit(&g_state, CBM_UI_ASSETS_CANCELLED, memory_order_release);+ ui_fill_error(err, err_sz, "load cancelled");+ return false;+ }+ if (!loaded) {+ ui_snapshot_free(&snapshot);+ atomic_store_explicit(&g_state, CBM_UI_ASSETS_FAILED, memory_order_release);+ ui_fill_error(err, err_sz, "verified pack not found");+ return false;+ }+ g_snapshot = snapshot;+ atomic_store_explicit(&g_state, CBM_UI_ASSETS_READY, memory_order_release);+ return true;+}++void cbm_ui_assets_request_cancel(void) {+ atomic_store_explicit(&g_cancel_requested, true, memory_order_release);+ int expected = CBM_UI_ASSETS_COLD;+ (void)atomic_compare_exchange_strong_explicit(&g_state, &expected, CBM_UI_ASSETS_CANCELLED,+ memory_order_acq_rel, memory_order_acquire);+}++cbm_ui_assets_state_t cbm_ui_assets_state(void) {+ if (!cbm_ui_assets_supported()) {+ return CBM_UI_ASSETS_UNAVAILABLE;+ }+ return (cbm_ui_assets_state_t)atomic_load_explicit(&g_state, memory_order_acquire);+}++const cbm_ui_asset_t *cbm_ui_asset_lookup(const char *path) {+ if (!path || cbm_ui_assets_state() != CBM_UI_ASSETS_READY) {+ return NULL;+ }+ size_t low = 0U;+ size_t high = g_snapshot.asset_count;+ while (low < high) {+ size_t middle = low + (high - low) / 2U;+ int compared = strcmp(path, g_snapshot.assets[middle].path);+ if (compared == 0) {+ return &g_snapshot.assets[middle];+ }+ if (compared < 0) {+ high = middle;+ } else {+ low = middle + 1U;+ }+ }+ return NULL;+}++bool cbm_ui_assets_stage_install(const char *install_dir,+ cbm_activation_transaction_t **transaction_out, char *err,+ size_t err_sz) {+ if (transaction_out) {+ *transaction_out = NULL;+ }+ if (!cbm_ui_assets_supported()) {+ return true;+ }+ if (!transaction_out || !install_dir || !install_dir[0] ||+ !cbm_ui_assets_warm(NULL, err, err_sz)) {+ if (!install_dir || !install_dir[0]) {+ ui_fill_error(err, err_sz, "install directory unavailable");+ }+ return false;+ }+ char stored[UI_PATH_CAP];+ if (!ui_candidate_path(install_dir, stored)) {+ ui_fill_error(err, err_sz, "install path is too long");+ return false;+ }+ if (!cbm_mkdir_p(install_dir, UI_ASSETS_DIR_PERM)) {+ ui_fill_error(err, err_sz, "cannot create the install directory");+ return false;+ }+ cbm_activation_transaction_status_t status = cbm_activation_transaction_stage_bytes(+ stored, g_snapshot.bytes, g_snapshot.length, transaction_out);+ if (status != CBM_ACTIVATION_TRANSACTION_OK || !*transaction_out) {+ if (*transaction_out) {+ (void)cbm_activation_transaction_close(transaction_out);+ }+ ui_fill_error(err, err_sz, "cannot stage the verified pack");+ return false;+ }+ return true;+}++static bool ui_install_validator(const char *target_path, void *context) {+ (void)context;+ return cbm_ui_assets_verify_file(target_path);+}++cbm_activation_transaction_status_t cbm_ui_assets_commit_install(+ cbm_activation_transaction_t *transaction) {+ if (!transaction) {+ return CBM_ACTIVATION_TRANSACTION_INVALID_ARGUMENT;+ }+ cbm_activation_transaction_status_t status =+ cbm_activation_transaction_commit(transaction, ui_install_validator, NULL);+#ifndef _WIN32+ if (status == CBM_ACTIVATION_TRANSACTION_OK) {+ const char *target = cbm_activation_transaction_target_path(transaction);+ if (!target || chmod(target, UI_ASSET_FILE_PERM) != 0) {+ cbm_activation_transaction_status_t rollback =+ cbm_activation_transaction_rollback(transaction);+ return rollback == CBM_ACTIVATION_TRANSACTION_OK+ ? CBM_ACTIVATION_TRANSACTION_IO+ : CBM_ACTIVATION_TRANSACTION_ROLLBACK_FAILED;+ }+ }+#endif+ return status;+}++cbm_activation_transaction_status_t cbm_ui_assets_commit_removal(+ cbm_activation_transaction_t *transaction) {+ if (!transaction) {+ return CBM_ACTIVATION_TRANSACTION_INVALID_ARGUMENT;+ }+ cbm_activation_transaction_status_t status =+ cbm_activation_transaction_commit(transaction, NULL, NULL);+ const char *retained = cbm_activation_transaction_backup_path(transaction);+ if (status != CBM_ACTIVATION_TRANSACTION_OK) {+ return status;+ }+ if (retained && cbm_ui_assets_verify_file(retained)) {+ return CBM_ACTIVATION_TRANSACTION_OK;+ }+ cbm_activation_transaction_status_t rollback =+ cbm_activation_transaction_rollback(transaction);+ return rollback == CBM_ACTIVATION_TRANSACTION_OK+ ? CBM_ACTIVATION_TRANSACTION_VALIDATION_FAILED+ : CBM_ACTIVATION_TRANSACTION_ROLLBACK_FAILED;+}++#ifdef CBM_CLI_ENABLE_TEST_API+bool cbm_ui_assets_install(const char *install_dir, bool dry_run, char *err, size_t err_sz) {+ if (!cbm_ui_assets_supported()) {+ return true;+ }+ if (!install_dir || !install_dir[0] || !cbm_ui_assets_warm(NULL, err, err_sz)) {+ if (!install_dir || !install_dir[0]) {+ ui_fill_error(err, err_sz, "install directory unavailable");+ }+ return false;+ }+ if (dry_run) {+ return true;+ }+ cbm_activation_transaction_t *transaction = NULL;+ if (!cbm_ui_assets_stage_install(install_dir, &transaction, err, err_sz)) {+ return false;+ }+ cbm_activation_transaction_status_t status = cbm_ui_assets_commit_install(transaction);+ if (status != CBM_ACTIVATION_TRANSACTION_OK) {+ (void)cbm_activation_transaction_close(&transaction);+ ui_fill_error(err, err_sz, "cannot publish the verified pack");+ return false;+ }+ status = cbm_activation_transaction_finalize(transaction);+ bool finalized =+ status == CBM_ACTIVATION_TRANSACTION_OK || status == CBM_ACTIVATION_TRANSACTION_DEFERRED;+ bool closed = cbm_activation_transaction_close(&transaction) == CBM_ACTIVATION_TRANSACTION_OK;+ if (!finalized || !closed) {+ ui_fill_error(err, err_sz, "cannot finalize the verified pack");+ return false;+ }+ return true;+}+#endif++bool cbm_ui_assets_remove(const char *install_dir, bool dry_run, char *err, size_t err_sz) {+ if (!cbm_ui_assets_supported()) {+ return true;+ }+ char path[UI_PATH_CAP];+ if (!ui_candidate_path(install_dir, path)) {+ ui_fill_error(err, err_sz, "uninstall path is too long");+ return false;+ }+ cbm_path_info_t info;+ if (cbm_path_info_utf8(path, &info) != 0) {+ return true;+ }+ ui_asset_snapshot_t verified = {0};+ if (!ui_try_path(path, &verified)) {+ ui_fill_error(err, err_sz, "adjacent pack is not owned; preserved");+ return false;+ }+ ui_snapshot_free(&verified);+ if (dry_run) {+ return true;+ }+ cbm_activation_transaction_t *transaction = NULL;+ cbm_activation_transaction_status_t status =+ cbm_activation_transaction_stage_removal(path, &transaction);+ if (status == CBM_ACTIVATION_TRANSACTION_OK && transaction) {+ status = cbm_ui_assets_commit_removal(transaction);+ }+ if (status != CBM_ACTIVATION_TRANSACTION_OK || !transaction) {+ (void)cbm_activation_transaction_close(&transaction);+ ui_fill_error(err, err_sz,+ status == CBM_ACTIVATION_TRANSACTION_VALIDATION_FAILED+ ? "adjacent pack changed before removal; preserved"+ : "cannot remove the owned adjacent pack");+ return false;+ }+ status = cbm_activation_transaction_finalize(transaction);+ bool finalized =+ status == CBM_ACTIVATION_TRANSACTION_OK || status == CBM_ACTIVATION_TRANSACTION_DEFERRED;+ bool closed = cbm_activation_transaction_close(&transaction) == CBM_ACTIVATION_TRANSACTION_OK;+ if (!finalized || !closed) {+ ui_fill_error(err, err_sz, "cannot finalize the owned adjacent pack removal");+ return false;+ }+ return true;+}++bool cbm_ui_assets_stage_remove(const char *install_dir,+ cbm_activation_transaction_t **transaction_out,+ bool *foreign_preserved_out, char *err, size_t err_sz) {+ if (transaction_out) {+ *transaction_out = NULL;+ }+ if (foreign_preserved_out) {+ *foreign_preserved_out = false;+ }+ if (!transaction_out) {+ ui_fill_error(err, err_sz, "uninstall transaction output unavailable");+ return false;+ }+ if (!cbm_ui_assets_supported()) {+ return true;+ }+ char path[UI_PATH_CAP];+ if (!install_dir || !install_dir[0] || !ui_candidate_path(install_dir, path)) {+ ui_fill_error(err, err_sz, "uninstall path is too long");+ return false;+ }+ cbm_path_info_t info;+ if (cbm_path_info_utf8(path, &info) != 0) {+ return true;+ }+ if (!info.is_regular || info.is_symlink || !cbm_ui_assets_verify_file(path)) {+ if (foreign_preserved_out) {+ *foreign_preserved_out = true;+ }+ return true;+ }+ cbm_activation_transaction_status_t status =+ cbm_activation_transaction_stage_removal(path, transaction_out);+ if (status != CBM_ACTIVATION_TRANSACTION_OK || !*transaction_out) {+ ui_fill_error(err, err_sz, cbm_activation_transaction_status_message(status));+ if (*transaction_out) {+ (void)cbm_activation_transaction_close(transaction_out);+ }+ return false;+ }+ /* Revalidate after the transaction captured target identity. Commit will+ * refuse if that identity changes before removal. */+ if (!cbm_ui_assets_verify_file(path)) {+ if (cbm_activation_transaction_close(transaction_out) != CBM_ACTIVATION_TRANSACTION_OK) {+ ui_fill_error(err, err_sz, "cannot clean up a changed pack removal transaction");+ return false;+ }+ if (foreign_preserved_out) {+ *foreign_preserved_out = true;+ }+ }+ return true;+}++#ifdef CBM_CLI_ENABLE_TEST_API+void cbm_ui_assets_set_manifest_for_testing(const char *name, const char *sha256, uint64_t size) {+ int name_written = snprintf(g_test_pack_name, sizeof(g_test_pack_name), "%s", name ? name : "");+ int hash_written = snprintf(g_test_sha256, sizeof(g_test_sha256), "%s", sha256 ? sha256 : "");+ g_test_manifest_set = name_written > 0 && (size_t)name_written < sizeof(g_test_pack_name) &&+ hash_written == CBM_SHA256_HEX_LEN;+ g_test_size = size;+}++void cbm_ui_assets_reset_for_testing(void) {+ ui_snapshot_free(&g_snapshot);+ atomic_store_explicit(&g_state, CBM_UI_ASSETS_COLD, memory_order_release);+ atomic_store_explicit(&g_cancel_requested, false, memory_order_release);+ g_binary_path[0] = '\0';+ g_test_manifest_set = false;+ g_test_pack_name[0] = '\0';+ g_test_sha256[0] = '\0';+ g_test_size = 0U;+}+#endifdiff --git a/src/ui/asset_pack.h b/src/ui/asset_pack.hnew file mode 100644index 000000000..c4af4be5e--- /dev/null+++ b/src/ui/asset_pack.h@@ -0,0 +1,111 @@+/*+ * asset_pack.h — Verified external frontend assets.+ *+ * UI builds embed only a content-addressed pack name, exact size and SHA-256.+ * The uncompressed pack stays outside the native executable and is read once+ * into an immutable process-lifetime snapshot before the HTTP listener starts.+ */+#ifndef CBM_UI_ASSET_PACK_H+#define CBM_UI_ASSET_PACK_H++#include <stdbool.h>+#include <stddef.h>+#include <stdint.h>++#include "cli/activation_transaction.h"++typedef enum {+ CBM_UI_ASSETS_UNAVAILABLE = 0,+ CBM_UI_ASSETS_COLD,+ CBM_UI_ASSETS_LOADING,+ CBM_UI_ASSETS_READY,+ CBM_UI_ASSETS_FAILED,+ CBM_UI_ASSETS_CANCELLED,+} cbm_ui_assets_state_t;++typedef enum {+ CBM_UI_ASSET_REVALIDATE = 1,+ CBM_UI_ASSET_IMMUTABLE = 2,+} cbm_ui_asset_cache_t;++typedef struct {+ const char *path;+ const unsigned char *data;+ size_t size;+ const char *content_type;+ cbm_ui_asset_cache_t cache;+} cbm_ui_asset_t;++/* Defined by asset_pack_stub.c for standard builds, asset_manifest_stub.c for+ * test runners, or the generated manifest for UI builds. No frontend payload+ * bytes live in any of them. */+extern const char CBM_UI_ASSET_PACK_NAME[];+extern const char CBM_UI_ASSET_SHA256[];+extern const uint64_t CBM_UI_ASSET_SIZE;++/* Compile-time capability; performs no filesystem I/O and is true before the+ * asynchronous warmup starts. */+bool cbm_ui_assets_supported(void);+const char *cbm_ui_assets_current_pack_name(void);++/* Exact binary path used to resolve the adjacent and package-share candidates.+ * Call before starting warmup. */+void cbm_ui_assets_set_binary_path(const char *path);++/* Resolve, hash and structurally validate the complete pack, then publish one+ * immutable lookup snapshot. A standard build is a successful no-op. */+bool cbm_ui_assets_warm(const char *home, char *err, size_t err_sz);+void cbm_ui_assets_request_cancel(void);+cbm_ui_assets_state_t cbm_ui_assets_state(void);++/* Returns NULL until the complete snapshot is READY. The returned view remains+ * valid for the process lifetime. */+const cbm_ui_asset_t *cbm_ui_asset_lookup(const char *path);++/* Direct CLI install publishes the verified content-addressed pack beside the+ * target executable before that executable becomes active. Uninstall removes+ * only an exact hash-verified adjacent pack. */+bool cbm_ui_assets_remove(const char *install_dir, bool dry_run, char *err, size_t err_sz);++/* Verify one explicit pack against this binary's compiled name/size/hash and+ * parser contract, without publishing a global snapshot. Standard builds+ * accept no pack and return true only through the supported() no-op paths. */+bool cbm_ui_assets_verify_file(const char *path);++/* Stage removal of the exact owned adjacent pack. Missing/standard packs are+ * successful no-ops; a foreign file is preserved and reported separately. */+bool cbm_ui_assets_stage_remove(const char *install_dir,+ cbm_activation_transaction_t **transaction_out,+ bool *foreign_preserved_out, char *err, size_t err_sz);++/* Commit an owned-pack removal only after the exact retained object (moved out+ * of the public name by the transaction) still verifies against this binary.+ * A same-inode rewrite after staging is rolled back and preserved. */+cbm_activation_transaction_status_t cbm_ui_assets_commit_removal(+ cbm_activation_transaction_t *transaction);++/* Stage the current verified content-addressed pack without publishing it.+ * Standard builds return true with a NULL transaction. UI callers retain the+ * transaction through the coordinated binary commit, then finalize/rollback+ * it while still holding the native activation guard. */+bool cbm_ui_assets_stage_install(const char *install_dir,+ cbm_activation_transaction_t **transaction_out, char *err,+ size_t err_sz);++/* Publish a staged pack with a post-rename parser/hash validator, binding the+ * verification to the bytes at the final public name before finalization. */+cbm_activation_transaction_status_t cbm_ui_assets_commit_install(+ cbm_activation_transaction_t *transaction);++#ifdef CBM_CLI_ENABLE_TEST_API+/* Focused lifecycle probe. Production publishes through stage_install as part+ * of the native guarded runtime-set transaction. */+bool cbm_ui_assets_install(const char *install_dir, bool dry_run, char *err, size_t err_sz);++/* Single-threaded test seams for exercising the parser with caller-created+ * fixtures whose digest is recomputed after each structural mutation. */+void cbm_ui_assets_set_manifest_for_testing(const char *name, const char *sha256, uint64_t size);+void cbm_ui_assets_reset_for_testing(void);+#endif++#endif /* CBM_UI_ASSET_PACK_H */diff --git a/src/ui/asset_pack_stub.c b/src/ui/asset_pack_stub.cnew file mode 100644index 000000000..9c4451cdf--- /dev/null+++ b/src/ui/asset_pack_stub.c@@ -0,0 +1,98 @@+/* Standard builds have no frontend pack and perform no UI asset I/O. */+#include "ui/asset_pack.h"++const char CBM_UI_ASSET_PACK_NAME[] = "";+const char CBM_UI_ASSET_SHA256[] = "";+const uint64_t CBM_UI_ASSET_SIZE = UINT64_C(0);++bool cbm_ui_assets_supported(void) {+ return false;+}++const char *cbm_ui_assets_current_pack_name(void) {+ return NULL;+}++void cbm_ui_assets_set_binary_path(const char *path) {+ (void)path;+}++bool cbm_ui_assets_warm(const char *home, char *err, size_t err_sz) {+ (void)home;+ (void)err;+ (void)err_sz;+ return true;+}++void cbm_ui_assets_request_cancel(void) {}++cbm_ui_assets_state_t cbm_ui_assets_state(void) {+ return CBM_UI_ASSETS_UNAVAILABLE;+}++const cbm_ui_asset_t *cbm_ui_asset_lookup(const char *path) {+ (void)path;+ return NULL;+}++#ifdef CBM_CLI_ENABLE_TEST_API+bool cbm_ui_assets_install(const char *install_dir, bool dry_run, char *err, size_t err_sz) {+ (void)install_dir;+ (void)dry_run;+ (void)err;+ (void)err_sz;+ return true;+}+#endif++bool cbm_ui_assets_remove(const char *install_dir, bool dry_run, char *err, size_t err_sz) {+ (void)install_dir;+ (void)dry_run;+ (void)err;+ (void)err_sz;+ return true;+}++bool cbm_ui_assets_verify_file(const char *path) {+ (void)path;+ return false;+}++bool cbm_ui_assets_stage_remove(const char *install_dir,+ cbm_activation_transaction_t **transaction_out,+ bool *foreign_preserved_out, char *err, size_t err_sz) {+ (void)install_dir;+ (void)err;+ (void)err_sz;+ if (transaction_out) {+ *transaction_out = NULL;+ }+ if (foreign_preserved_out) {+ *foreign_preserved_out = false;+ }+ return transaction_out != NULL;+}++bool cbm_ui_assets_stage_install(const char *install_dir,+ cbm_activation_transaction_t **transaction_out, char *err,+ size_t err_sz) {+ (void)install_dir;+ (void)err;+ (void)err_sz;+ if (transaction_out) {+ *transaction_out = NULL;+ }+ return transaction_out != NULL;+}++cbm_activation_transaction_status_t cbm_ui_assets_commit_install(+ cbm_activation_transaction_t *transaction) {+ return transaction ? CBM_ACTIVATION_TRANSACTION_INVALID_ARGUMENT+ : CBM_ACTIVATION_TRANSACTION_OK;+}++cbm_activation_transaction_status_t cbm_ui_assets_commit_removal(+ cbm_activation_transaction_t *transaction) {+ return transaction ? CBM_ACTIVATION_TRANSACTION_INVALID_ARGUMENT+ : CBM_ACTIVATION_TRANSACTION_OK;+}diff --git a/src/ui/config.c b/src/ui/config.cindex 0694f7e77..76d8f9d8c 100644--- a/src/ui/config.c+++ b/src/ui/config.c@@ -6,7 +6,7 @@*/#include "foundation/constants.h"#include "ui/config.h"-#include "ui/embedded_assets.h"+#include "ui/asset_pack.h"#include "foundation/log.h"#include "foundation/platform.h"#include "foundation/compat_fs.h"@@ -122,8 +122,9 @@ void cbm_ui_config_load(cbm_ui_config_t *cfg) {bool opened = false;char *buffer = config_read_file(path, &length, &opened);if (!opened) {- /* No config file — auto-enable UI if binary has embedded assets */- if (CBM_EMBEDDED_FILE_COUNT > 0) {+ /* Capability does not transiently disappear while the daemon warms+ * the verified external pack asynchronously. */+ if (cbm_ui_assets_supported()) {cfg->ui_enabled = true;}return;diff --git a/src/ui/embedded_assets.h b/src/ui/embedded_assets.hdeleted file mode 100644index 5ea1b3ddc..000000000--- a/src/ui/embedded_assets.h+++ /dev/null@@ -1,25 +0,0 @@-/*- * embedded_assets.h — Interface for embedded frontend assets.- *- * When built with `cbm-with-ui`, the embed script generates embedded_assets.c- * with actual file data. Otherwise, embedded_stub.c provides an empty array.- */-#ifndef CBM_UI_EMBEDDED_ASSETS_H-#define CBM_UI_EMBEDDED_ASSETS_H--typedef struct {- const char *path; /* URL path, e.g. "/index.html" */- const unsigned char *data; /* raw file bytes */- unsigned int size; /* byte count */- const char *content_type; /* MIME type, e.g. "text/html" */-} cbm_embedded_file_t;--/* Array of embedded files + count. Defined in embedded_assets.c or embedded_stub.c.- * Not const — sizes are initialized at startup by a constructor function. */-extern cbm_embedded_file_t CBM_EMBEDDED_FILES[];-extern const int CBM_EMBEDDED_FILE_COUNT;--/* Look up an embedded file by URL path. Returns NULL if not found. */-const cbm_embedded_file_t *cbm_embedded_lookup(const char *path);--#endif /* CBM_UI_EMBEDDED_ASSETS_H */diff --git a/src/ui/embedded_stub.c b/src/ui/embedded_stub.cdeleted file mode 100644index 240a94afe..000000000--- a/src/ui/embedded_stub.c+++ /dev/null@@ -1,22 +0,0 @@-/*- * embedded_stub.c — Empty asset table when built without frontend.- *- * Used by the standard `cbm` target (no Node.js required).- * The `cbm-with-ui` target replaces this with generated embedded_assets.c.- */-#include "ui/embedded_assets.h"--#include <stddef.h>-#include <string.h>--cbm_embedded_file_t CBM_EMBEDDED_FILES[] = {{NULL, NULL, 0, NULL}};-const int CBM_EMBEDDED_FILE_COUNT = 0;--const cbm_embedded_file_t *cbm_embedded_lookup(const char *path) {- for (int i = 0; i < CBM_EMBEDDED_FILE_COUNT; i++) {- if (strcmp(CBM_EMBEDDED_FILES[i].path, path) == 0) {- return &CBM_EMBEDDED_FILES[i];- }- }- return NULL;-}diff --git a/src/ui/http_server.c b/src/ui/http_server.cindex 991a34cda..1a951819c 100644--- a/src/ui/http_server.c+++ b/src/ui/http_server.c@@ -3,8 +3,8 @@** Transport (sockets, parsing, limits) lives in httpd.c; this file owns* the routes and their handlers:- * GET / → embedded index.html- * GET /assets/... → embedded JS/CSS+ * GET / → verified external index.html+ * GET /assets/... → verified external JS/CSS* POST /rpc → JSON-RPC dispatch via own cbm_mcp_server_t* OPTIONS /rpc → CORS preflight (for vite dev on :5173)* GET/POST /api/... → UI support endpoints (layout, index, browse, …)@@ -15,7 +15,7 @@*/#include "ui/http_server.h"#include "ui/httpd.h"-#include "ui/embedded_assets.h"+#include "ui/asset_pack.h"#include "ui/layout3d.h"#include "mcp/mcp.h"#include "store/store.h"@@ -29,6 +29,8 @@/* pipeline.h no longer needed — indexing runs as subprocess */#include "foundation/log.h"#include "foundation/platform.h"+#include "foundation/secure_random.h"+#include "foundation/sha256.h"#include "foundation/compat.h"#include "foundation/compat_fs.h"#include "foundation/str_util.h"@@ -180,9 +182,11 @@ struct cbm_http_server {atomic_int run_state;int port;bool listener_ok;+ uint8_t readiness_secret[CBM_SHA256_DIGEST_LEN];+ bool readiness_secret_set;};-/* ── Serve embedded asset ─────────────────────────────────────── */+/* ── Serve verified frontend asset ───────────────────────────── *//* Content-Security-Policy for the served UI. No external host appears in any* directive, so the browser cannot load or connect to anything off-origin —@@ -197,19 +201,22 @@ struct cbm_http_server {"style-src 'self' 'unsafe-inline'; font-src 'self' data:; " \"worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'\r\n"-static bool serve_embedded(cbm_http_conn_t *c, const char *path) {- const cbm_embedded_file_t *f = cbm_embedded_lookup(path);+static bool serve_frontend_asset(cbm_http_conn_t *c, const char *path) {+ const cbm_ui_asset_t *f = cbm_ui_asset_lookup(path);if (!f)return false;/* Build headers with correct Content-Type for this asset */char hdrs[1024];+ const char *cache = f->cache == CBM_UI_ASSET_REVALIDATE+ ? "Cache-Control: no-cache\r\n"+ : "Cache-Control: public, max-age=31536000, immutable\r\n";snprintf(hdrs, sizeof(hdrs),"%sContent-Type: %s\r\n"- "Cache-Control: public, max-age=31536000, immutable\r\n" CBM_UI_CSP,- g_cors, f->content_type);+ "%sX-Content-Type-Options: nosniff\r\n" CBM_UI_CSP,+ g_cors, f->content_type, cache);- cbm_http_reply_buf(c, 200, hdrs, f->data, (size_t)f->size);+ cbm_http_reply_buf(c, 200, hdrs, f->data, f->size);return true;}@@ -936,15 +943,7 @@ static bool resolve_self_executable(char *out, size_t outsz) {}#elsestatic bool resolve_self_executable(char *out, size_t outsz) {- /* GetModuleFileNameA renders the module path through the ANSI code page,- * which mangles non-ASCII install paths (café_日本語 -> caf?_???). Resolve- * wide and convert to UTF-8 so the returned path survives verbatim. */- wchar_t wbuf[1024];- DWORD n = GetModuleFileNameW(NULL, wbuf, (DWORD)(sizeof(wbuf) / sizeof(wbuf[0])));- if (n == 0 || n >= sizeof(wbuf) / sizeof(wbuf[0])) {- return false;- }- char *utf8 = cbm_wide_to_utf8(wbuf);+ char *utf8 = cbm_module_path_utf8();if (!utf8) {return false;}@@ -993,6 +992,7 @@ void cbm_http_server_set_binary_path(const char *path) {g_binary_path[0] = '\0';}}+ cbm_ui_assets_set_binary_path(g_binary_path);}/* Execute through the daemon's shared job registry. The thread is retained in@@ -1716,6 +1716,77 @@ static bool content_type_is_json(const char *content_type) {return *suffix == '\0' || *suffix == ';';}+static int readiness_hex_nibble(char value) {+ if (value >= '0' && value <= '9') {+ return value - '0';+ }+ if (value >= 'a' && value <= 'f') {+ return value - 'a' + 10;+ }+ return -1;+}++static bool readiness_hex_decode(const char *hex, uint8_t out[CBM_SHA256_DIGEST_LEN]) {+ if (!hex || strlen(hex) != CBM_SHA256_HEX_LEN) {+ return false;+ }+ for (size_t i = 0; i < CBM_SHA256_DIGEST_LEN; i++) {+ int high = readiness_hex_nibble(hex[i * 2U]);+ int low = readiness_hex_nibble(hex[i * 2U + 1U]);+ if (high < 0 || low < 0) {+ return false;+ }+ out[i] = (uint8_t)((high << 4) | low);+ }+ return true;+}++static void readiness_hex_encode(const uint8_t bytes[CBM_SHA256_DIGEST_LEN],+ char out[CBM_SHA256_HEX_LEN + 1U]) {+ static const char hex[] = "0123456789abcdef";+ for (size_t i = 0; i < CBM_SHA256_DIGEST_LEN; i++) {+ out[i * 2U] = hex[bytes[i] >> 4];+ out[i * 2U + 1U] = hex[bytes[i] & 0x0fU];+ }+ out[CBM_SHA256_HEX_LEN] = '\0';+}++static void handle_ui_readiness(cbm_http_server_t *srv, cbm_http_conn_t *c,+ const cbm_http_req_t *req) {+ if (!srv->readiness_secret_set) {+ cbm_http_replyf(c, 503, "Cache-Control: no-store\r\n", "%s", "readiness proof unavailable");+ return;+ }+ char challenge_hex[CBM_SHA256_HEX_LEN + 1U];+ uint8_t challenge[CBM_SHA256_DIGEST_LEN];+ static const char prefix[] = "challenge=";+ if (strncmp(req->query, prefix, sizeof(prefix) - 1U) != 0 ||+ strlen(req->query) != sizeof(prefix) - 1U + CBM_SHA256_HEX_LEN) {+ cbm_http_replyf(c, 400, "Cache-Control: no-store\r\n", "%s", "invalid challenge");+ return;+ }+ memcpy(challenge_hex, req->query + sizeof(prefix) - 1U, CBM_SHA256_HEX_LEN);+ challenge_hex[CBM_SHA256_HEX_LEN] = '\0';+ if (!readiness_hex_decode(challenge_hex, challenge)) {+ cbm_secure_zero(challenge, sizeof(challenge));+ cbm_http_replyf(c, 400, "Cache-Control: no-store\r\n", "%s", "invalid challenge");+ return;+ }+ uint8_t proof[CBM_SHA256_DIGEST_LEN];+ char proof_hex[CBM_SHA256_HEX_LEN + 1U];+ cbm_hmac_sha256(srv->readiness_secret, sizeof(srv->readiness_secret), challenge,+ sizeof(challenge), proof);+ readiness_hex_encode(proof, proof_hex);+ cbm_http_replyf(c, 200,+ "Content-Type: text/plain; charset=utf-8\r\n"+ "Cache-Control: no-store\r\n"+ "X-Content-Type-Options: nosniff\r\n",+ "%s", proof_hex);+ cbm_secure_zero(challenge, sizeof(challenge));+ cbm_secure_zero(proof, sizeof(proof));+ cbm_secure_zero(proof_hex, sizeof(proof_hex));+}+static bool request_passes_http_security(cbm_http_server_t *srv, cbm_http_conn_t *c,const cbm_http_req_t *req) {if (req->http_minor == 1 && req->host[0] == '\0') {@@ -1756,6 +1827,14 @@ static void dispatch_request(cbm_http_server_t *srv, cbm_http_conn_t *c,return;}+ /* Private-generation proof used only by `daemon start --open`. The+ * challenge is public; the HMAC key exists only in this daemon's+ * authenticated application and HTTP server instances. */+ if (is_get && strcmp(req->path, "/__cbm/ui-readiness") == 0) {+ handle_ui_readiness(srv, c, req);+ return;+ }+/* POST /rpc → JSON-RPC dispatch (reuses existing MCP tools) */if (is_post && cbm_http_path_match(req->path, "/rpc")) {handle_rpc(c, req, srv->mcp);@@ -1836,20 +1915,23 @@ static void dispatch_request(cbm_http_server_t *srv, cbm_http_conn_t *c,/* GET / → index.html (no-cache so browser always gets latest) */if (cbm_http_path_match(req->path, "/")) {- const cbm_embedded_file_t *f = cbm_embedded_lookup("/index.html");+ const cbm_ui_asset_t *f = cbm_ui_asset_lookup("/index.html");if (f) {char html_hdrs[1024];snprintf(html_hdrs, sizeof(html_hdrs),- "%sContent-Type: text/html\r\nCache-Control: no-cache\r\n" CBM_UI_CSP, g_cors);- cbm_http_reply_buf(c, 200, html_hdrs, f->data, (size_t)f->size);+ "%sContent-Type: text/html; charset=utf-8\r\nCache-Control: no-cache\r\n"+ "X-Content-Type-Options: nosniff\r\n" CBM_UI_CSP,+ g_cors);+ cbm_http_reply_buf(c, 200, html_hdrs, f->data, f->size);return;}- cbm_http_replyf(c, 404, g_cors, "no frontend embedded");+ cbm_http_replyf(c, 503, "Cache-Control: no-store\r\nRetry-After: 1\r\n",+ "frontend assets are not ready");return;}- /* GET /assets/... → embedded assets, then generic embedded fallback */- if (serve_embedded(c, req->path))+ /* GET /assets/... → exact lookup in the immutable verified pack. */+ if (serve_frontend_asset(c, req->path))return;cbm_http_replyf(c, 404, g_cors, "not found");@@ -1927,6 +2009,7 @@ bool cbm_http_server_free(cbm_http_server_t *srv) {if (!cbm_httpd_close(srv->listener))return false;cbm_mcp_server_free(srv->mcp);+ cbm_secure_zero(srv->readiness_secret, sizeof(srv->readiness_secret));free(srv);return true;}@@ -2043,3 +2126,13 @@ void cbm_http_server_set_project_mutation_guard(cbm_http_server_t *srv,cbm_mcp_server_set_project_mutation_guard(srv->mcp, begin, end, begin ? context : NULL);cbm_mcp_server_set_project_mutation_try_guard(srv->mcp, begin);}++void cbm_http_server_set_readiness_secret(cbm_http_server_t *srv,+ const uint8_t secret[CBM_SHA256_DIGEST_LEN]) {+ if (!srv || !secret ||+ atomic_load_explicit(&srv->run_state, memory_order_acquire) != HTTP_RUN_IDLE) {+ return;+ }+ memcpy(srv->readiness_secret, secret, sizeof(srv->readiness_secret));+ srv->readiness_secret_set = true;+}diff --git a/src/ui/http_server.h b/src/ui/http_server.hindex 7e536023e..ef54593a4 100644--- a/src/ui/http_server.h+++ b/src/ui/http_server.h@@ -2,7 +2,7 @@* http_server.h — Embedded HTTP server for the graph visualization UI.** Binds to 127.0.0.1:<port> only (localhost).- * Serves embedded frontend assets and proxies /rpc to a dedicated+ * Serves the verified external frontend pack and proxies /rpc to a dedicated* read-only cbm_mcp_server_t instance.** Runs in a background pthread, same pattern as the watcher thread.@@ -11,6 +11,7 @@#define CBM_UI_HTTP_SERVER_H#include "ui/httpd.h"+#include "foundation/sha256.h"#include <stdbool.h>#include <stddef.h>@@ -75,6 +76,12 @@ void cbm_http_server_set_project_mutation_guard(cbm_http_server_t *srv,cbm_http_project_mutation_end_fn end,void *context);+/* Copy the daemon generation's private readiness secret into the server+ * before its run loop starts. GET /__cbm/ui-readiness returns only a+ * challenge-bound HMAC proof; the secret itself is never served. */+void cbm_http_server_set_readiness_secret(cbm_http_server_t *srv,+ const uint8_t secret[CBM_SHA256_DIGEST_LEN]);+/* Initialize the log ring buffer mutex. Must be called once before any threads. */void cbm_ui_log_init(void);diff --git a/src/ui/httpd.h b/src/ui/httpd.hindex dccfbe072..2719667d5 100644--- a/src/ui/httpd.h+++ b/src/ui/httpd.h@@ -116,7 +116,7 @@ void cbm_http_replyf(cbm_http_conn_t *c, int status, const char *extra_headers,#endif;-/* Binary-safe variant for embedded assets. */+/* Binary-safe variant for verified asset-pack entries. */void cbm_http_reply_buf(cbm_http_conn_t *c, int status, const char *extra_headers, const void *data,size_t len);diff --git a/test-infrastructure/vm/vm-smoke.sh b/test-infrastructure/vm/vm-smoke.shindex 308c5c863..3641594c6 100755--- a/test-infrastructure/vm/vm-smoke.sh+++ b/test-infrastructure/vm/vm-smoke.sh@@ -19,7 +19,7 @@ Usage: [env] bash test-infrastructure/vm/vm-smoke.shThe canonical WINDOWS smoke entry: identical in local CI (win.shsmoke-install), PR CI (pr.yml) and the release venues (_smoke.yml). Stages a-complete single-binary release fixture under a disposable profile root,+complete one-executable runtime-set fixture under a disposable profile root,serves it on a kernel-assigned port, prepares/verifies/cleans the user-PATHregistry via windows-user-path-guard.ps1, neutralizes every agent-configdestination override, then runs scripts/smoke-test.sh (all phases).@@ -28,14 +28,15 @@ 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:+ SMOKE_VARIANT standard (default) | ui. ui requires the external UI pack:Phase 15's "no assets" SKIP becomes a FAILURE, so a standardbinary cannot pass a ui run.CBM_SMOKE_ARTIFACT_DIRRelease 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.+ (codebase-memory-mcp.exe + cbm-integrations.json + LICENSE ++ install.ps1 + THIRD_PARTY_NOTICES.md + the UI pack when selected). The+ exact variant set is served verbatim; an incomplete archive+ fails the smoke.Unset (default): stages the freshly built binary out ofbuild/c and synthesizes the sidecars (local/PR mode).@@ -75,9 +76,9 @@ case "$SMOKE_ARCH" inarm64 | 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+# A ui run must be handed a binary with exactly one external asset pack beside+# it; the suffix alone only renames the archive. SMOKE_REQUIRE_UI turns Phase+# 15's documented "no UI assets" SKIP into a failure, so asking for ui and# supplying a standard binary can no longer pass quietly.case "$SMOKE_VARIANT" instandard) SUFFIX="" ; REQUIRE_UI=0 ;;@@ -85,6 +86,37 @@ ui) SUFFIX="-ui" ; REQUIRE_UI=1 ;;*) echo "vm-smoke: SMOKE_VARIANT must be standard or ui. Please consult --help." >&2; exit 2 ;;esac+if [ -n "$ARTIFACT_DIR" ]; then+ UI_PACK_SOURCE_DIR="$ARTIFACT_DIR"+else+ UI_PACK_SOURCE_DIR="$(dirname "$BINARY_SRC")"+fi+shopt -s nullglob+UI_PACK_CANDIDATES=("$UI_PACK_SOURCE_DIR"/cbm-ui-*.pack)+shopt -u nullglob+UI_PACK_COUNT=0+UI_PACK_NAME=""+UI_PACK_SOURCE=""+for candidate in "${UI_PACK_CANDIDATES[@]+"${UI_PACK_CANDIDATES[@]}"}"; do+ UI_PACK_COUNT=$((UI_PACK_COUNT + 1))+ UI_PACK_SOURCE="$candidate"+ candidate_name="$(basename "$candidate")"+ if ! [[ "$candidate_name" =~ ^cbm-ui-[0-9a-f]{64}\.pack$ ]]; then+ echo "vm-smoke: invalid UI pack name beside artifact: $candidate_name" >&2+ exit 2+ fi+done+if [ "$SMOKE_VARIANT" = "ui" ]; then+ if [ "$UI_PACK_COUNT" -ne 1 ] || [ ! -s "$UI_PACK_SOURCE" ]; then+ echo "vm-smoke: ui fixture requires exactly one content-addressed UI pack" >&2+ exit 2+ fi+ UI_PACK_NAME="$(basename "$UI_PACK_SOURCE")"+elif [ "$UI_PACK_COUNT" -ne 0 ]; then+ echo "vm-smoke: standard fixture must not contain a UI asset pack" >&2+ exit 2+fi+PROFILE_ROOT="$(cygpath -u "$USERPROFILE")"SMOKE_DIR="$(mktemp -d "$PROFILE_ROOT/cbm-vm-smoke.XXXXXX")"FIXTURE_DIR="$SMOKE_DIR/artifacts"@@ -146,6 +178,10 @@ MSYS2_ARG_CONV_EXCL='*' powershell.exe -NoProfile -ExecutionPolicy Bypass \-SmokeRoot "$(cygpath -w "$SMOKE_DIR")"cp "$BINARY_SRC" "$SMOKE_DIR/codebase-memory-mcp.exe"cp "$SMOKE_DIR/codebase-memory-mcp.exe" "$FIXTURE_DIR/"+if [ -n "$UI_PACK_SOURCE" ]; then+ cp "$UI_PACK_SOURCE" "$SMOKE_DIR/$UI_PACK_NAME"+ cp "$UI_PACK_SOURCE" "$FIXTURE_DIR/$UI_PACK_NAME"+fi# The integration asset must sit next to the smoke binary in $SMOKE_DIR: phases# that invoke it directly (Phase 14 stages it by hand and drives an uninstall)# resolve the asset next to the binary, and without it those render-template@@ -175,11 +211,12 @@ fiEXPECTED_ARTIFACT="codebase-memory-mcp${SUFFIX}-windows-${SMOKE_ARCH}.zip"(cd "$FIXTURE_DIR"- zip -q "$EXPECTED_ARTIFACT" \- codebase-memory-mcp.exe cbm-integrations.json LICENSE install.ps1 THIRD_PARTY_NOTICES.md- if [ -n "$SUFFIX" ]; then- cp "$EXPECTED_ARTIFACT" "codebase-memory-mcp-windows-${SMOKE_ARCH}.zip"- fi+ ARCHIVE_MEMBERS=(+ codebase-memory-mcp.exe cbm-integrations.json LICENSE install.ps1+ THIRD_PARTY_NOTICES.md+ )+ [ -n "$UI_PACK_NAME" ] && ARCHIVE_MEMBERS+=("$UI_PACK_NAME")+ zip -q "$EXPECTED_ARTIFACT" "${ARCHIVE_MEMBERS[@]}"sha256sum *.zip > checksums.txt)diff --git a/test-infrastructure/vm/win.sh b/test-infrastructure/vm/win.shindex 659d61203..2f373e21a 100755--- a/test-infrastructure/vm/win.sh+++ b/test-infrastructure/vm/win.sh@@ -102,10 +102,15 @@ USER_="${CBM_VM_USER:-test}"# Unset (the default) keeps the historical single-tree behaviour.VM_BASE_REPO="/c/cbm"if [ -n "${CBM_CI_RUN_ID:-}" ]; then+ if [[ ! "$CBM_CI_RUN_ID" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]]; then+ echo "FATAL: CBM_CI_RUN_ID must match [A-Za-z0-9][A-Za-z0-9._-]{0,63}." >&2+ exit 2+ fiVM_REPO="/c/cbm-run-${CBM_CI_RUN_ID}"elseVM_REPO="$VM_BASE_REPO"fi+VM_REPO_WIN="C:\\${VM_REPO#/c/}"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}}"@@ -185,12 +190,12 @@ vm_preflight() {return 0}vm_cmd "powershell -NoProfile -ExecutionPolicy Bypass -File \-C:\\cbm\\scripts\\ci\\clean-test-residue.ps1 -MinFreeGB ${CBM_VM_MIN_FREE_GB:-14}"+${VM_REPO_WIN}\\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"+${VM_REPO_WIN}\\scripts\\ci\\ensure-defender.ps1"}cmd="${1:-status}"; shift || true@@ -198,10 +203,16 @@ case "$cmd" instatus | help | -h | --help) ;;*) cbm_vm_sync_windows_clock "${SSH[@]}" ;;esac+# An isolated update/sync needs its checkout before the checkout-owned+# preflight scripts can run. Other venue commands deliberately fail preflight+# when their requested checkout has not been established by update/sync.+case "$cmd" in+update | sync) vm_ensure_run_checkout ;;+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) ;;+status | sh | push-file | pageheap | drop-run-checkout | help | -h | --help) ;;*) vm_preflight ;;esaccase "$cmd" in@@ -210,7 +221,6 @@ status)vm clangarm64 "cd $VM_REPO 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_ensure_run_checkoutvm clangarm64 "cd $VM_REPO && git fetch origin ${BRANCH} && git reset --hard FETCH_HEAD && git clean -fdx && git log --oneline -1"exec "$0" build;;@@ -225,7 +235,6 @@ drop-run-checkout)fi;;sync)- vm_ensure_run_checkoutlocal_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")"@@ -243,14 +252,12 @@ sync)vm clangarm64 \"cd $VM_REPO && 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 $VM_REPO && git apply --binary --whitespace=nowarn -"' \+ vm clangarm64 \+ "cd '$VM_REPO' && git apply --binary --whitespace=nowarn -" \<"$WIN_PATCH"fiif [ -s "$WIN_MANIFEST" ]; then- "${SSH[@]}" \- 'C:\msys64\msys2_shell.cmd -defterm -no-start -clangarm64 -c "cd $VM_REPO && tar -xf -"' \- <"$WIN_ARCHIVE"+ vm clangarm64 "cd '$VM_REPO' && tar -xf -" <"$WIN_ARCHIVE"fivm clangarm64 "cd $VM_REPO && git status --short --branch"win_cleanup@@ -280,7 +287,8 @@ test)[ -z "${CBM_VM_EXPECT_HEAD:-}" ] || vm_assert_head "$CBM_VM_EXPECT_HEAD";;guards)- # Match the Windows CI product build: a clean, embedded-UI product binary.+ # Match the Windows CI product build: a clean UI product runtime set with+ # its external, content-addressed pack.# 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@@ -297,7 +305,7 @@ guards)# different environment shape than CI's profile-rooted TEMP. Python must# be PREPENDED: the Microsoft Store python.exe alias stub lives early in# the profile PATH and otherwise shadows any appended interpreter.- vm_cmd "cd /d C:\\cbm && set PATH=C:\\msys64\\clangarm64\\bin;C:\\msys64\\usr\\bin;%PATH%&& powershell -NoProfile -ExecutionPolicy Bypass -File scripts\\test-windows.ps1 -GuardsOnly -Binary build\\guards\\codebase-memory-mcp.exe -Make C:\\msys64\\usr\\bin\\make.exe"+ vm_cmd "cd /d ${VM_REPO_WIN} && 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 canonicaldiff --git a/tests/fixtures/ui-readiness/index.html b/tests/fixtures/ui-readiness/index.htmlnew file mode 100644index 000000000..36872848c--- /dev/null+++ b/tests/fixtures/ui-readiness/index.html@@ -0,0 +1,10 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <title>Codebase Memory — UI readiness fixture</title>+ </head>+ <body>+ <div id="root"></div>+ </body>+</html>diff --git a/tests/test_c_lsp.c b/tests/test_c_lsp.cindex d821ad30b..db2ac2f2e 100644--- a/tests/test_c_lsp.c+++ b/tests/test_c_lsp.c@@ -15066,8 +15066,9 @@ TEST(clsp_easy_win_sfinaevoid_t) {PASS();}-/* DLL resolve LSP tests removed — string literals triggered- * Windows Defender false positive. See issue #89. */+/* DLL resolve LSP tests removed after the associated builds received a+ * Windows Defender verdict. The opaque verdict did not prove which feature+ * caused it; see issue #89 for the historical observation. */TEST(clsp_dll_custom_resolver) {CBMFileResult *r = extract_c("\n"diff --git a/tests/test_cli.c b/tests/test_cli.cindex 789a6fc4e..2ac2c579d 100644--- a/tests/test_cli.c+++ b/tests/test_cli.c@@ -10,6 +10,7 @@* Total: 47 Go tests → 47 C tests*/#include "../src/foundation/compat.h"+#include "../src/foundation/compat_fs.h"#include "../src/foundation/compat_thread.h"#include "test_framework.h"#include "test_helpers.h"@@ -23,7 +24,10 @@#include <daemon/version_cohort.h>#include <foundation/constants.h>#include <foundation/platform.h>+#include <foundation/secure_random.h>+#include <foundation/sha256.h>#include <mcp/mcp.h>+#include <ui/asset_pack.h>#include <foundation/yaml.h>#include <store/store.h>#include <yyjson/yyjson.h>@@ -35,6 +39,9 @@#include <sys/stat.h>#include <unistd.h>#ifndef _WIN32+#include <fcntl.h>+#include <signal.h>+#include <sys/file.h>#include <sys/wait.h>#endif#ifdef __APPLE__@@ -44,6 +51,10 @@#include <limits.h>#include <zlib.h>+#ifndef CBM_VERSION+#define CBM_VERSION "dev"+#endif+/* Internal prompt seam used to restore process-global state after command* tests that exercise --yes. */void cbm_set_auto_answer_for_test(int value);@@ -393,7 +404,9 @@ typedef struct {const char *guarded_text_a;const char *guarded_path_b;const char *guarded_text_b;+ const char *guarded_absent_path;bool guarded_files_visible_before_unlock;+ bool guarded_path_absent_before_unlock;int mutation_reserve_result;int mutation_reserve_count;int quiesce_count;@@ -436,6 +449,11 @@ static void cli_activation_fake_release_mutation(void *opaque, cbm_cli_activatiopath_b_visible = data && (!fake->guarded_text_b || strstr(data, fake->guarded_text_b));}fake->guarded_files_visible_before_unlock |= path_a_visible && path_b_visible;+ if (fake->guarded_absent_path) {+ cbm_path_info_t ignored;+ fake->guarded_path_absent_before_unlock =+ cbm_path_info_utf8(fake->guarded_absent_path, &ignored) != 0;+ }fake->mutation_lease_held = false;fake->mutation_lease_release_count++;if (fake->release_marker) {@@ -466,21 +484,17 @@ static cbm_cli_activation_ops_t cli_activation_fake_ops(cli_activation_fake_t *freturn ops;}-/* Every install/update/uninstall in this suite dispatches through here. On- * Windows a test that has not installed its own activation ops gets a default- * fake for the duration of the command: without the seam, `update` (correctly)- * hands off to install.ps1 before the shared agent-config logic these tests- * verify ever runs. POSIX behavior is untouched — tests without ops keep- * exercising the real activation machinery. */+/* Ordinary command fixtures test install/config/runtime mutations, not the+ * account-global daemon belonging to the developer running the suite. Give+ * every platform a process-local successful activation guard unless a test+ * installed explicit ops. Dedicated activation tests below call production+ * entry points directly with an isolated runtime parent. This also keeps the+ * Windows update handoff from bypassing the shared config logic under test. */static cli_activation_fake_t g_cli_test_seam_fake;static cbm_cli_activation_ops_t g_cli_test_seam_ops;static int cli_test_cmd_dispatch(int (*command)(int, char **), int argc, char **argv) {-#ifdef _WIN32bool engage = !cbm_cli_activation_test_ops_installed();-#else- bool engage = false;-#endifif (engage) {memset(&g_cli_test_seam_fake, 0, sizeof(g_cli_test_seam_fake));g_cli_test_seam_fake.mutation_reserve_result = 1;@@ -528,6 +542,62 @@ static void cli_activation_restore_env(char *home, char *cache) {free(cache);}+/* Bind the fixture boundary itself. Without the automatic seam POSIX used the+ * account-global production endpoint, so unrelated config tests could refuse+ * (or attempt to stop) the developer's live CBM daemon. The explicit private+ * runtime parent makes the pre-fix path safe for RED-on-revert: production can+ * succeed there, but these fake-guard counters remain zero. */+TEST(cli_command_fixtures_isolate_activation_from_live_account) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-command-isolation-XXXXXX");+ if (!cbm_mkdtemp(tmpdir)) {+ FAIL("cbm_mkdtemp failed");+ }+ char runtime_parent[512];+ char cache_dir[512];+ char bin_dir[512];+ snprintf(runtime_parent, sizeof(runtime_parent), "%s/runtime", tmpdir);+ snprintf(cache_dir, sizeof(cache_dir), "%s/cache", tmpdir);+ snprintf(bin_dir, sizeof(bin_dir), "%s/bin", tmpdir);+ if (test_mkdirp(runtime_parent) != 0 || test_mkdirp(cache_dir) != 0 ||+ test_mkdirp(bin_dir) != 0) {+ test_rmdir_r(tmpdir);+ FAIL("isolated command fixture setup failed");+ }++ char *old_home = NULL;+ char *old_cache = NULL;+ cli_activation_save_env(&old_home, &old_cache);+ char *old_path = save_test_env("PATH");+ char *old_assets = save_test_env("CBM_ASSETS_DIR");+ cbm_setenv("HOME", tmpdir, 1);+ cbm_setenv("CBM_CACHE_DIR", cache_dir, 1);+ cbm_setenv("PATH", bin_dir, 1);+ cbm_unsetenv("CBM_ASSETS_DIR");+ cbm_integration_assets_reset_for_testing();+ cbm_cli_set_activation_ops_for_test(NULL);+ cbm_cli_set_activation_runtime_parent_for_test(runtime_parent);++ char dir_arg[640];+ snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", bin_dir);+ char *argv[] = {"uninstall", "--yes", dir_arg};+ int rc = cli_test_cmd_uninstall(3, argv);++ cbm_cli_set_activation_runtime_parent_for_test(NULL);+ cbm_cli_set_activation_ops_for_test(NULL);+ restore_test_env("PATH", old_path);+ restore_test_env("CBM_ASSETS_DIR", old_assets);+ cbm_integration_assets_reset_for_testing();+ cli_activation_restore_env(old_home, old_cache);+ test_rmdir_r(tmpdir);++ ASSERT_EQ(rc, 0);+ ASSERT_EQ(g_cli_test_seam_fake.mutation_reserve_count, 1);+ ASSERT_EQ(g_cli_test_seam_fake.mutation_lease_release_count, 1);+ ASSERT_FALSE(cbm_cli_activation_test_ops_installed());+ PASS();+}+/* Helper: create tar.gz with a single file */static unsigned char *create_test_targz(const char *filename, const unsigned char *content,int content_len, int *out_len) {@@ -911,7 +981,7 @@ TEST(cli_activation_quiesce_does_not_wait_on_bootstrap_startup) {char dir_arg[640];snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", install_dir);char *install_argv[] = {"--force", "--skip-config", "--yes", dir_arg};- int install_rc = child_ready ? cli_test_cmd_install(4, install_argv) : -1;+ int install_rc = child_ready ? cbm_cmd_install(4, install_argv) : -1;cbm_cli_set_activation_runtime_parent_for_test(NULL);cbm_set_auto_answer_for_test(0);@@ -1241,6 +1311,9 @@ TEST(cli_install_config_and_path_finish_before_guard_release) {char shell_rc[512];char bin_dir[512];char bin_target[640];+ char fixed_asset[640];+ char owned_asset_dir[640];+ char owned_asset[768];snprintf(codex_dir, sizeof(codex_dir), "%s/.codex", tmpdir);snprintf(codex_config, sizeof(codex_config), "%s/config.toml", codex_dir);snprintf(shell_rc, sizeof(shell_rc), "%s/.zshrc", tmpdir);@@ -1253,7 +1326,16 @@ TEST(cli_install_config_and_path_finish_before_guard_release) {#elsesnprintf(bin_target, sizeof(bin_target), "%s/codebase-memory-mcp", bin_dir);#endif+ snprintf(fixed_asset, sizeof(fixed_asset), "%s/cbm-integrations.json", bin_dir);+ ASSERT_TRUE(cbm_integration_assets_ownership_path(tmpdir, owned_asset, sizeof(owned_asset)));+ snprintf(owned_asset_dir, sizeof(owned_asset_dir), "%s", owned_asset);+ char *owned_separator = strrchr(owned_asset_dir, '/');+ ASSERT_NOT_NULL(owned_separator);+ *owned_separator = '\0';+ test_mkdirp(owned_asset_dir);write_test_file(bin_target, "existing binary selected by the user");+ write_test_file(fixed_asset, "assets owned by the kept executable\n");+ write_test_file(owned_asset, "ownership reference for the kept executable\n");cli_activation_fake_t fake = {.mutation_reserve_result = 1,@@ -1273,6 +1355,14 @@ TEST(cli_install_config_and_path_finish_before_guard_release) {cbm_cli_set_activation_ops_for_test(NULL);cbm_set_auto_answer_for_test(0);+ char *fixed_after = read_test_file_alloc(fixed_asset);+ char *owned_after = read_test_file_alloc(owned_asset);+ bool kept_runtime_assets =+ fixed_after && strcmp(fixed_after, "assets owned by the kept executable\n") == 0 &&+ owned_after && strcmp(owned_after, "ownership reference for the kept executable\n") == 0;+ free(fixed_after);+ free(owned_after);+if (old_shell) {cbm_setenv("SHELL", old_shell, 1);} else {@@ -1286,14 +1376,15 @@ TEST(cli_install_config_and_path_finish_before_guard_release) {ASSERT_EQ(fake.mutation_reserve_count, 1);ASSERT_EQ(fake.mutation_lease_release_count, 1);ASSERT_TRUE(fake.guarded_files_visible_before_unlock);+ ASSERT_TRUE(kept_runtime_assets);PASS();}-/* Regression: config installation is not atomic across every supported agent.- * Once the verified executable has been published, rolling only that binary- * back on one agent-config refusal leaves any successful config writes pointing- * at the wrong (or, for a fresh install, missing) executable. */-TEST(cli_install_config_failure_keeps_published_binary) {+/* A failed candidate install must not strand a half-new runtime set. The fixed+ * adjacent integration asset and content-addressed ownership reference are committed+ * before the executable, but all three retain their backups until the guarded+ * install succeeds. */+TEST(cli_install_config_failure_restores_previous_runtime_set) {char tmpdir[256];snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-install-partial-config-XXXXXX");if (!cbm_mkdtemp(tmpdir)) {@@ -1313,6 +1404,9 @@ TEST(cli_install_config_failure_keeps_published_binary) {char openclaw_config[640];char bin_dir[512];char bin_target[640];+ char fixed_asset[640];+ char owned_asset_dir[640];+ char owned_asset[768];snprintf(cache_dir, sizeof(cache_dir), "%s/cache", tmpdir);snprintf(openclaw_dir, sizeof(openclaw_dir), "%s/.openclaw", tmpdir);snprintf(openclaw_config, sizeof(openclaw_config), "%s/openclaw.json", openclaw_dir);@@ -1322,11 +1416,24 @@ TEST(cli_install_config_failure_keeps_published_binary) {#elsesnprintf(bin_target, sizeof(bin_target), "%s/codebase-memory-mcp", bin_dir);#endif+ snprintf(fixed_asset, sizeof(fixed_asset), "%s/cbm-integrations.json", bin_dir);+ ASSERT_TRUE(cbm_integration_assets_ownership_path(tmpdir, owned_asset, sizeof(owned_asset)));+ snprintf(owned_asset_dir, sizeof(owned_asset_dir), "%s", owned_asset);+ char *owned_separator = strrchr(owned_asset_dir, '/');+ ASSERT_NOT_NULL(owned_separator);+ *owned_separator = '\0';cbm_setenv("CBM_CACHE_DIR", cache_dir, 1);test_mkdirp(openclaw_dir);test_mkdirp(bin_dir);+ test_mkdirp(owned_asset_dir);const char *malformed = "{ invalid config\n";+ const char *old_binary = "previous executable\n";+ const char *old_fixed_asset = "previous fixed integration asset\n";+ const char *old_owned_asset = "previous ownership reference\n";write_test_file(openclaw_config, malformed);+ write_test_file(bin_target, old_binary);+ write_test_file(fixed_asset, old_fixed_asset);+ write_test_file(owned_asset, old_owned_asset);cli_activation_fake_t fake = {.mutation_reserve_result = 1,@@ -1338,8 +1445,15 @@ TEST(cli_install_config_failure_keeps_published_binary) {cbm_cli_set_activation_ops_for_test(NULL);cbm_set_auto_answer_for_test(0);- struct stat binary_status;- bool binary_published = stat(bin_target, &binary_status) == 0;+ char *binary_after = read_test_file_alloc(bin_target);+ char *fixed_after = read_test_file_alloc(fixed_asset);+ char *owned_after = read_test_file_alloc(owned_asset);+ bool runtime_restored = binary_after && strcmp(binary_after, old_binary) == 0 && fixed_after &&+ strcmp(fixed_after, old_fixed_asset) == 0 && owned_after &&+ strcmp(owned_after, old_owned_asset) == 0;+ free(binary_after);+ free(fixed_after);+ free(owned_after);char *after = read_test_file_alloc(openclaw_config);bool malformed_preserved = after && strcmp(after, malformed) == 0;free(after);@@ -1349,14 +1463,413 @@ TEST(cli_install_config_failure_keeps_published_binary) {test_rmdir_r(tmpdir);ASSERT_EQ(rc, 1);- ASSERT_TRUE(binary_published);+ ASSERT_TRUE(runtime_restored);ASSERT_TRUE(malformed_preserved);ASSERT_EQ(fake.mutation_reserve_count, 1);ASSERT_EQ(fake.mutation_lease_release_count, 1);- ASSERT_NOT_NULL(strstr(fake.diagnostic, "executable was kept"));PASS();}+typedef struct {+ const char *binary_target;+ const char *old_pack;+ bool old_pack_present_at_binary_publish;+} cli_runtime_publish_probe_t;++static void cli_runtime_publish_probe(const char *target_path, void *opaque) {+ cli_runtime_publish_probe_t *probe = opaque;+ if (!probe || !target_path || strcmp(target_path, probe->binary_target) != 0) {+ return;+ }+ cbm_path_info_t info;+ probe->old_pack_present_at_binary_publish =+ cbm_path_info_utf8(probe->old_pack, &info) == 0 && info.is_regular && !info.is_symlink;+}++/* A standard install following a UI install must remove the old pack while it+ * still owns the activation lease, but only after the new binary is active.+ * A hash-shaped foreign file whose bytes do not match its name is preserved. */+TEST(cli_install_gc_is_guarded_content_bound_and_after_binary_publish) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-runtime-pack-gc-XXXXXX");+ if (!cbm_mkdtemp(tmpdir)) {+ FAIL("cbm_mkdtemp failed");+ }+ char *old_home = NULL;+ char *old_cache = NULL;+ cli_activation_save_env(&old_home, &old_cache);+ char *old_path = save_test_env("PATH");+ char *old_shell = save_test_env("SHELL");+ char bin_dir[512];+ char bin_target[640];+ char cache_dir[512];+ snprintf(bin_dir, sizeof(bin_dir), "%s/bin", tmpdir);+ snprintf(cache_dir, sizeof(cache_dir), "%s/cache", tmpdir);+#ifdef _WIN32+ snprintf(bin_target, sizeof(bin_target), "%s/codebase-memory-mcp.exe", bin_dir);+#else+ snprintf(bin_target, sizeof(bin_target), "%s/codebase-memory-mcp", bin_dir);+#endif+ test_mkdirp(bin_dir);+ cbm_setenv("HOME", tmpdir, 1);+ cbm_setenv("CBM_CACHE_DIR", cache_dir, 1);+ cbm_setenv("PATH", bin_dir, 1);+ cbm_setenv("SHELL", "/bin/false", 1);++ static const char old_pack_bytes[] = "previous verified UI pack bytes\n";+ char scratch_pack[640];+ char old_pack[768];+ char old_digest[CBM_SHA256_HEX_LEN + 1U];+ snprintf(scratch_pack, sizeof(scratch_pack), "%s/stale-pack-source", bin_dir);+ write_test_file(scratch_pack, old_pack_bytes);+ ASSERT_EQ(cbm_cli_sha256_file(scratch_pack, old_digest, sizeof(old_digest)), 0);+ snprintf(old_pack, sizeof(old_pack), "%s/cbm-ui-%s.pack", bin_dir, old_digest);+ ASSERT_EQ(rename(scratch_pack, old_pack), 0);++ char foreign_pack[768];+ snprintf(foreign_pack, sizeof(foreign_pack),+ "%s/cbm-ui-0000000000000000000000000000000000000000000000000000000000000000.pack",+ bin_dir);+ write_test_file(foreign_pack, "foreign bytes do not match the filename\n");++ cli_runtime_publish_probe_t probe = {+ .binary_target = bin_target,+ .old_pack = old_pack,+ };+ cbm_activation_transaction_set_before_absent_publish_for_test(cli_runtime_publish_probe,+ &probe);+ cli_activation_fake_t fake = {+ .mutation_reserve_result = 1,+ .guarded_absent_path = old_pack,+ };+ cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake);+ cbm_cli_set_activation_ops_for_test(&ops);+ char dir_arg[640];+ snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", bin_dir);+ char *argv[] = {"--force", "--yes", "--skip-config", dir_arg};+ int rc = cli_test_cmd_install(4, argv);+ cbm_cli_set_activation_ops_for_test(NULL);+ cbm_activation_transaction_set_before_absent_publish_for_test(NULL, NULL);+ cbm_set_auto_answer_for_test(0);++ cbm_path_info_t ignored;+ bool verified_stale_removed = cbm_path_info_utf8(old_pack, &ignored) != 0;+ bool foreign_preserved = cbm_path_info_utf8(foreign_pack, &ignored) == 0;+ restore_test_env("PATH", old_path);+ restore_test_env("SHELL", old_shell);+ cli_activation_restore_env(old_home, old_cache);+ test_rmdir_r(tmpdir);++ ASSERT_EQ(rc, 0);+ ASSERT_TRUE(probe.old_pack_present_at_binary_publish);+ ASSERT_TRUE(verified_stale_removed);+ ASSERT_TRUE(foreign_preserved);+ ASSERT_TRUE(fake.guarded_path_absent_before_unlock);+ ASSERT_EQ(fake.mutation_lease_release_count, 1);+ PASS();+}++#ifndef _WIN32+enum {+ CLI_TEST_UI_PACK_HEADER_BYTES = 80,+ CLI_TEST_UI_PACK_ENTRY_BYTES = 24,+};++static void cli_test_ui_write_u16(unsigned char *bytes, uint16_t value) {+ bytes[0] = (unsigned char)value;+ bytes[1] = (unsigned char)(value >> 8U);+}++static void cli_test_ui_write_u32(unsigned char *bytes, uint32_t value) {+ for (size_t index = 0U; index < sizeof(value); index++) {+ bytes[index] = (unsigned char)(value >> (index * 8U));+ }+}++static void cli_test_ui_write_u64(unsigned char *bytes, uint64_t value) {+ for (size_t index = 0U; index < sizeof(value); index++) {+ bytes[index] = (unsigned char)(value >> (index * 8U));+ }+}++static bool cli_test_write_ui_pack(const char *directory, char path_out[1024], char name_out[128],+ char hash_out[65], size_t *size_out) {+ static const char asset_path[] = "/assets/app.js";+ static const char index_path[] = "/index.html";+ static const unsigned char asset_data[] = "console.log('runtime-set');";+ static const unsigned char index_data[] = "<h1>runtime set</h1>";+ size_t paths_length = sizeof(asset_path) - 1U + sizeof(index_path) - 1U;+ size_t payload_length = sizeof(asset_data) - 1U + sizeof(index_data) - 1U;+ size_t index_length = CLI_TEST_UI_PACK_ENTRY_BYTES * 2U;+ size_t paths_offset = CLI_TEST_UI_PACK_HEADER_BYTES + index_length;+ size_t payload_offset = paths_offset + paths_length;+ size_t total = payload_offset + payload_length;+ unsigned char *pack = calloc(total, 1U);+ if (!pack) {+ return false;+ }+ memcpy(pack, "CBMUIPK", 7U);+ cli_test_ui_write_u16(pack + 8U, 1U);+ cli_test_ui_write_u16(pack + 10U, CLI_TEST_UI_PACK_HEADER_BYTES);+ cli_test_ui_write_u32(pack + 16U, 2U);+ cli_test_ui_write_u32(pack + 20U, CLI_TEST_UI_PACK_ENTRY_BYTES);+ cli_test_ui_write_u64(pack + 24U, CLI_TEST_UI_PACK_HEADER_BYTES);+ cli_test_ui_write_u64(pack + 32U, index_length);+ cli_test_ui_write_u64(pack + 40U, paths_offset);+ cli_test_ui_write_u64(pack + 48U, paths_length);+ cli_test_ui_write_u64(pack + 56U, payload_offset);+ cli_test_ui_write_u64(pack + 64U, payload_length);+ cli_test_ui_write_u64(pack + 72U, total);++ unsigned char *asset = pack + CLI_TEST_UI_PACK_HEADER_BYTES;+ cli_test_ui_write_u16(asset + 4U, sizeof(asset_path) - 1U);+ asset[6U] = 2U;+ asset[7U] = CBM_UI_ASSET_IMMUTABLE;+ cli_test_ui_write_u64(asset + 16U, sizeof(asset_data) - 1U);+ unsigned char *index = asset + CLI_TEST_UI_PACK_ENTRY_BYTES;+ cli_test_ui_write_u32(index, sizeof(asset_path) - 1U);+ cli_test_ui_write_u16(index + 4U, sizeof(index_path) - 1U);+ index[6U] = 1U;+ index[7U] = CBM_UI_ASSET_REVALIDATE;+ cli_test_ui_write_u64(index + 8U, sizeof(asset_data) - 1U);+ cli_test_ui_write_u64(index + 16U, sizeof(index_data) - 1U);+ memcpy(pack + paths_offset, asset_path, sizeof(asset_path) - 1U);+ memcpy(pack + paths_offset + sizeof(asset_path) - 1U, index_path, sizeof(index_path) - 1U);+ memcpy(pack + payload_offset, asset_data, sizeof(asset_data) - 1U);+ memcpy(pack + payload_offset + sizeof(asset_data) - 1U, index_data, sizeof(index_data) - 1U);+ cbm_sha256_hex(pack, total, hash_out);+ int name_length = snprintf(name_out, 128U, "cbm-ui-%s.pack", hash_out);+ int path_length = snprintf(path_out, 1024U, "%s/%s", directory, name_out);+ FILE *file = name_length > 0 && name_length < 128 && path_length > 0 && path_length < 1024+ ? cbm_fopen(path_out, "wb")+ : NULL;+ bool written = file && fwrite(pack, 1U, total, file) == total;+ if (file && fclose(file) != 0) {+ written = false;+ }+ free(pack);+ if (written) {+ *size_out = total;+ }+ return written;+}++typedef struct {+ const char *lock_path;+ const char *first_locked_path;+ const char *second_waiting_path;+ const char *observed_pack_path;+ const char *observed_pack_marker;+ bool first;+ int descriptor;+} cli_install_order_lock_t;++static int cli_install_order_reserve(void *opaque, cbm_cli_activation_lock_t *lease_out) {+ cli_install_order_lock_t *lock = opaque;+ *lease_out = NULL;+ lock->descriptor = open(lock->lock_path, O_CREAT | O_RDWR, 0600);+ if (lock->descriptor < 0) {+ return -1;+ }+ if (!lock->first) {+ (void)write_test_file(lock->second_waiting_path, "waiting\n");+ }+ if (flock(lock->descriptor, LOCK_EX) != 0) {+ (void)close(lock->descriptor);+ lock->descriptor = -1;+ return -1;+ }+ if (lock->first) {+ (void)write_test_file(lock->first_locked_path, "locked\n");+ bool second_waiting = false;+ for (int attempt = 0; attempt < 10000; attempt++) {+ struct stat status;+ if (stat(lock->second_waiting_path, &status) == 0) {+ second_waiting = true;+ break;+ }+ cbm_usleep(1000);+ }+ if (!second_waiting) {+ (void)flock(lock->descriptor, LOCK_UN);+ (void)close(lock->descriptor);+ lock->descriptor = -1;+ return -1;+ }+ } else if (lock->observed_pack_path && lock->observed_pack_marker) {+ cbm_path_info_t info;+ if (cbm_path_info_utf8(lock->observed_pack_path, &info) == 0 && info.is_regular &&+ !info.is_symlink) {+ (void)write_test_file(lock->observed_pack_marker, "observed\n");+ }+ }+ *lease_out = lock;+ return 1;+}++static void cli_install_order_release(void *opaque, cbm_cli_activation_lock_t lease) {+ cli_install_order_lock_t *lock = opaque;+ if (lease == lock && lock->descriptor >= 0) {+ (void)flock(lock->descriptor, LOCK_UN);+ (void)close(lock->descriptor);+ lock->descriptor = -1;+ }+}++static void cli_install_order_diagnostic(void *opaque, const char *message) {+ (void)opaque;+ (void)message;+}++static bool cli_wait_child_bounded(pid_t child, int *status_out) {+ for (int attempt = 0; attempt < 30000; attempt++) {+ pid_t waited = waitpid(child, status_out, WNOHANG);+ if (waited == child) {+ return true;+ }+ if (waited < 0 && errno != EINTR) {+ return false;+ }+ cbm_usleep(1000);+ }+ (void)kill(child, SIGKILL);+ while (waitpid(child, status_out, 0) < 0 && errno == EINTR) {}+ return false;+}++static int cli_install_order_child(const char *home, const char *bin_dir, const char *source_dir,+ const char *pack_name, const char *pack_hash, size_t pack_size,+ cli_install_order_lock_t *lock, bool ui_variant) {+ cbm_setenv("HOME", home, 1);+ cbm_setenv("CBM_CACHE_DIR", home, 1);+ cbm_setenv("PATH", bin_dir, 1);+ cbm_setenv("SHELL", "/bin/false", 1);+ cbm_ui_assets_reset_for_testing();+ if (ui_variant) {+ cbm_setenv("CBM_UI_ASSETS_DIR", source_dir, 1);+ cbm_ui_assets_set_manifest_for_testing(pack_name, pack_hash, pack_size);+ } else {+ cbm_unsetenv("CBM_UI_ASSETS_DIR");+ }+ cbm_cli_activation_ops_t ops = {+ .context = lock,+ .reserve_for_mutation = cli_install_order_reserve,+ .mutation_lease_release = cli_install_order_release,+ .visible_diagnostic = cli_install_order_diagnostic,+ };+ cbm_cli_set_activation_ops_for_test(&ops);+ char dir_arg[640];+ snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", bin_dir);+ char *argv[] = {"--force", "--yes", "--skip-config", dir_arg};+ return cbm_cmd_install(4, argv);+}++/* Deterministic UI->standard contention: UI owns the lease, standard reaches+ * the same lease and blocks, then standard commits last. The final set must be+ * standard (no UI pack); deleting outside the guard leaves the UI pack behind. */+TEST(cli_concurrent_ui_then_standard_install_leaves_coherent_standard_set) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-runtime-set-race-XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmpdir));+ char home[512];+ char bin_dir[512];+ char source_dir[512];+ char lock_path[512];+ char first_locked[512];+ char second_waiting[512];+ char ui_pack_observed[512];+ snprintf(home, sizeof(home), "%s/home", tmpdir);+ snprintf(bin_dir, sizeof(bin_dir), "%s/bin", tmpdir);+ snprintf(source_dir, sizeof(source_dir), "%s/ui-source", tmpdir);+ snprintf(lock_path, sizeof(lock_path), "%s/activation.lock", tmpdir);+ snprintf(first_locked, sizeof(first_locked), "%s/ui-locked", tmpdir);+ snprintf(second_waiting, sizeof(second_waiting), "%s/standard-waiting", tmpdir);+ snprintf(ui_pack_observed, sizeof(ui_pack_observed), "%s/ui-pack-observed", tmpdir);+ test_mkdirp(home);+ test_mkdirp(bin_dir);+ test_mkdirp(source_dir);+ char source_pack[1024];+ char pack_name[128];+ char pack_hash[65];+ size_t pack_size = 0U;+ ASSERT_TRUE(cli_test_write_ui_pack(source_dir, source_pack, pack_name, pack_hash, &pack_size));+ char installed_pack[1024];+ snprintf(installed_pack, sizeof(installed_pack), "%s/%s", bin_dir, pack_name);++ cli_install_order_lock_t ui_lock = {+ .lock_path = lock_path,+ .first_locked_path = first_locked,+ .second_waiting_path = second_waiting,+ .first = true,+ .descriptor = -1,+ };+ pid_t ui_child = fork();+ if (ui_child == 0) {+ int child_rc = cli_install_order_child(home, bin_dir, source_dir, pack_name, pack_hash,+ pack_size, &ui_lock, true);+ _exit(child_rc == 0 ? 0 : 1);+ }+ if (ui_child < 0) {+ test_rmdir_r(tmpdir);+ FAIL("could not fork the UI installer child");+ }+ bool ui_locked = false;+ for (int attempt = 0; attempt < 10000; attempt++) {+ struct stat status;+ if (stat(first_locked, &status) == 0) {+ ui_locked = true;+ break;+ }+ cbm_usleep(1000);+ }+ if (!ui_locked) {+ (void)kill(ui_child, SIGKILL);+ (void)waitpid(ui_child, NULL, 0);+ test_rmdir_r(tmpdir);+ FAIL("UI child did not acquire the deterministic activation lease");+ }++ cli_install_order_lock_t standard_lock = {+ .lock_path = lock_path,+ .first_locked_path = first_locked,+ .second_waiting_path = second_waiting,+ .observed_pack_path = installed_pack,+ .observed_pack_marker = ui_pack_observed,+ .first = false,+ .descriptor = -1,+ };+ pid_t standard_child = fork();+ if (standard_child == 0) {+ int child_rc = cli_install_order_child(home, bin_dir, source_dir, pack_name, pack_hash,+ pack_size, &standard_lock, false);+ _exit(child_rc == 0 ? 0 : 1);+ }+ if (standard_child < 0) {+ (void)kill(ui_child, SIGKILL);+ (void)waitpid(ui_child, NULL, 0);+ test_rmdir_r(tmpdir);+ FAIL("could not fork the standard installer child");+ }+ int ui_status = 0;+ int standard_status = 0;+ bool ui_reaped_cleanly = cli_wait_child_bounded(ui_child, &ui_status);+ bool standard_reaped_cleanly = cli_wait_child_bounded(standard_child, &standard_status);+ cbm_path_info_t ignored;+ bool final_pack_absent = cbm_path_info_utf8(installed_pack, &ignored) != 0;+ bool ui_pack_was_visible_to_standard = cbm_path_info_utf8(ui_pack_observed, &ignored) == 0;+ test_rmdir_r(tmpdir);+ ASSERT_TRUE(ui_reaped_cleanly);+ ASSERT_TRUE(standard_reaped_cleanly);+ ASSERT_TRUE(WIFEXITED(ui_status));+ ASSERT_EQ(WEXITSTATUS(ui_status), 0);+ ASSERT_TRUE(WIFEXITED(standard_status));+ ASSERT_EQ(WEXITSTATUS(standard_status), 0);+ ASSERT_TRUE(ui_pack_was_visible_to_standard);+ ASSERT_TRUE(final_pack_absent);+ PASS();+}+#endif+TEST(cli_update_download_failure_does_not_quiesce_sessions) {char tmpdir[256];snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-daemon-update-XXXXXX");@@ -1746,6 +2259,158 @@ TEST(cli_uninstall_preserves_binary_and_index_when_cohort_does_not_drain) {PASS();}+TEST(cli_uninstall_custom_dir_removes_exact_owned_runtime_set) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-uninstall-runtime-set-XXXXXX");+ if (!cbm_mkdtemp(tmpdir)) {+ FAIL("cbm_mkdtemp failed");+ }+ char *old_home = NULL;+ char *old_cache = NULL;+ cli_activation_save_env(&old_home, &old_cache);+ char *old_assets = save_test_env("CBM_ASSETS_DIR");+ cbm_setenv("HOME", tmpdir, 1);++ char cache_dir[512];+ char bin_dir[512];+ char bin_target[640];+ char adjacent_asset[640];+ char ownership_asset[768];+ char ownership_dir[768];+ snprintf(cache_dir, sizeof(cache_dir), "%s/cache", tmpdir);+ snprintf(bin_dir, sizeof(bin_dir), "%s/custom/program", tmpdir);+#ifdef _WIN32+ snprintf(bin_target, sizeof(bin_target), "%s/codebase-memory-mcp.exe", bin_dir);+#else+ snprintf(bin_target, sizeof(bin_target), "%s/codebase-memory-mcp", bin_dir);+#endif+ snprintf(adjacent_asset, sizeof(adjacent_asset), "%s/cbm-integrations.json", bin_dir);+ ASSERT_TRUE(+ cbm_integration_assets_ownership_path(tmpdir, ownership_asset, sizeof(ownership_asset)));+ snprintf(ownership_dir, sizeof(ownership_dir), "%s", ownership_asset);+ char *ownership_separator = strrchr(ownership_dir, '/');+ ASSERT_NOT_NULL(ownership_separator);+ *ownership_separator = '\0';+ test_mkdirp(cache_dir);+ test_mkdirp(bin_dir);+ test_mkdirp(ownership_dir);+ cbm_setenv("CBM_CACHE_DIR", cache_dir, 1);++ char *asset_bytes = read_test_file_alloc("assets/cbm-integrations.json");+ ASSERT_NOT_NULL(asset_bytes);+ write_test_file(bin_target, "custom installed binary\n");+ write_test_file(adjacent_asset, asset_bytes);+ write_test_file(ownership_asset, asset_bytes);+ free(asset_bytes);+ cbm_setenv("CBM_ASSETS_DIR", bin_dir, 1);+ cbm_integration_assets_reset_for_testing();++ cli_activation_fake_t fake = {+ .mutation_reserve_result = 1,+ .guarded_absent_path = ownership_asset,+ };+ cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake);+ cbm_cli_set_activation_ops_for_test(&ops);+ char dir_arg[640];+ snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", bin_dir);+ char *argv[] = {"--yes", dir_arg};+ int rc = cli_test_cmd_uninstall(2, argv);+ cbm_cli_set_activation_ops_for_test(NULL);+ cbm_set_auto_answer_for_test(0);++ cbm_path_info_t ignored;+ bool binary_removed = cbm_path_info_utf8(bin_target, &ignored) != 0;+ bool adjacent_removed = cbm_path_info_utf8(adjacent_asset, &ignored) != 0;+ bool ownership_removed = cbm_path_info_utf8(ownership_asset, &ignored) != 0;+ restore_test_env("CBM_ASSETS_DIR", old_assets);+ cbm_integration_assets_reset_for_testing();+ cli_activation_restore_env(old_home, old_cache);+ test_rmdir_r(tmpdir);++ ASSERT_EQ(rc, 0);+ ASSERT_TRUE(binary_removed);+ ASSERT_TRUE(adjacent_removed);+ ASSERT_TRUE(ownership_removed);+ ASSERT_EQ(fake.mutation_reserve_count, 1);+ ASSERT_EQ(fake.mutation_lease_release_count, 1);+ ASSERT_TRUE(fake.guarded_path_absent_before_unlock);+ PASS();+}++TEST(cli_uninstall_preserves_foreign_integration_sidecar) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-uninstall-foreign-sidecar-XXXXXX");+ if (!cbm_mkdtemp(tmpdir)) {+ FAIL("cbm_mkdtemp failed");+ }+ char *old_home = NULL;+ char *old_cache = NULL;+ cli_activation_save_env(&old_home, &old_cache);+ char *old_assets = save_test_env("CBM_ASSETS_DIR");+ cbm_setenv("HOME", tmpdir, 1);+ char cache_dir[512];+ char bin_dir[512];+ char bin_target[640];+ char adjacent_asset[640];+ char ownership_asset[768];+ char ownership_dir[768];+ snprintf(cache_dir, sizeof(cache_dir), "%s/cache", tmpdir);+ snprintf(bin_dir, sizeof(bin_dir), "%s/custom/program", tmpdir);+#ifdef _WIN32+ snprintf(bin_target, sizeof(bin_target), "%s/codebase-memory-mcp.exe", bin_dir);+#else+ snprintf(bin_target, sizeof(bin_target), "%s/codebase-memory-mcp", bin_dir);+#endif+ snprintf(adjacent_asset, sizeof(adjacent_asset), "%s/cbm-integrations.json", bin_dir);+ ASSERT_TRUE(+ cbm_integration_assets_ownership_path(tmpdir, ownership_asset, sizeof(ownership_asset)));+ snprintf(ownership_dir, sizeof(ownership_dir), "%s", ownership_asset);+ char *ownership_separator = strrchr(ownership_dir, '/');+ ASSERT_NOT_NULL(ownership_separator);+ *ownership_separator = '\0';+ test_mkdirp(cache_dir);+ test_mkdirp(bin_dir);+ test_mkdirp(ownership_dir);+ cbm_setenv("CBM_CACHE_DIR", cache_dir, 1);+ char *asset_bytes = read_test_file_alloc("assets/cbm-integrations.json");+ ASSERT_NOT_NULL(asset_bytes);+ write_test_file(bin_target, "custom installed binary\n");+ write_test_file(adjacent_asset, "foreign integration asset\n");+ write_test_file(ownership_asset, asset_bytes);+ free(asset_bytes);+ cbm_setenv("CBM_ASSETS_DIR", ownership_dir, 1);+ cbm_integration_assets_reset_for_testing();++ cli_activation_fake_t fake = {.mutation_reserve_result = 1};+ cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake);+ cbm_cli_set_activation_ops_for_test(&ops);+ char dir_arg[640];+ snprintf(dir_arg, sizeof(dir_arg), "--dir=%s", bin_dir);+ char *argv[] = {"--yes", dir_arg};+ int rc = cli_test_cmd_uninstall(2, argv);+ cbm_cli_set_activation_ops_for_test(NULL);+ cbm_set_auto_answer_for_test(0);++ char *foreign_after = read_test_file_alloc(adjacent_asset);+ bool foreign_preserved =+ foreign_after && strcmp(foreign_after, "foreign integration asset\n") == 0;+ free(foreign_after);+ cbm_path_info_t ignored;+ bool binary_removed = cbm_path_info_utf8(bin_target, &ignored) != 0;+ bool ownership_removed = cbm_path_info_utf8(ownership_asset, &ignored) != 0;+ restore_test_env("CBM_ASSETS_DIR", old_assets);+ cbm_integration_assets_reset_for_testing();+ cli_activation_restore_env(old_home, old_cache);+ test_rmdir_r(tmpdir);++ ASSERT_EQ(rc, 0);+ ASSERT_TRUE(binary_removed);+ ASSERT_TRUE(ownership_removed);+ ASSERT_TRUE(foreign_preserved);+ ASSERT_EQ(fake.mutation_lease_release_count, 1);+ PASS();+}+TEST(cli_activation_guard_is_bypassed_for_dry_run_and_plan) {char tmpdir[256];snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-daemon-stateless-XXXXXX");@@ -9699,24 +10364,54 @@ TEST(cli_integration_assets_tampered_or_missing_fail_closed) {PASS();}-#ifndef CBM_VERSION-#define CBM_VERSION "dev"+TEST(cli_runtime_asset_probe_requires_exact_adjacent_set) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-runtime-probe-XXXXXX");+ if (!cbm_mkdtemp(tmpdir)) {+ FAIL("cbm_mkdtemp failed");+ }+ char binary_path[512];+ char asset_path[512];+#ifdef _WIN32+ snprintf(binary_path, sizeof(binary_path), "%s/codebase-memory-mcp.exe", tmpdir);+#else+ snprintf(binary_path, sizeof(binary_path), "%s/codebase-memory-mcp", tmpdir);#endif+ snprintf(asset_path, sizeof(asset_path), "%s/cbm-integrations.json", tmpdir);+ write_test_file(binary_path, "probe binary identity\n");+ char *asset_bytes = read_test_file_alloc("assets/cbm-integrations.json");+ ASSERT_NOT_NULL(asset_bytes);+ write_test_file(asset_path, asset_bytes);+ free(asset_bytes);+ char err[512] = {0};+ bool exact_ok = cbm_cli_verify_runtime_assets_at(binary_path, err, sizeof(err));+ write_test_file(asset_path, "modified sidecar\n");+ bool tampered_refused = !cbm_cli_verify_runtime_assets_at(binary_path, err, sizeof(err));+ bool actionable = strstr(err, "do not match this binary") != NULL;+ test_rmdir_r(tmpdir);+ ASSERT_TRUE(exact_ok);+ ASSERT_TRUE(tampered_refused);+ ASSERT_TRUE(actionable);+ PASS();+}-/* `install` persists the verified bytes to <home>/.cbm/assets/<version>/ —+/* `install` persists the verified bytes to <home>/.cbm/assets/<sha256>/ —* a sibling of the disposable cache, never inside it. That stored copy is* the OWNERSHIP REFERENCE uninstall materializes templates from after the* release archive is gone, so it must exist, re-verify, and never be* written by a dry run. */-TEST(cli_integration_assets_install_stores_versioned_ownership_copy) {+TEST(cli_integration_assets_install_stores_content_addressed_ownership_copy) {char tmpdir[256];snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-assets-store-XXXXXX");if (!cbm_mkdtemp(tmpdir))FAIL("cbm_mkdtemp failed");char stored_dir[512];char stored_path[640];- snprintf(stored_dir, sizeof(stored_dir), "%s/.cbm/assets/%s", tmpdir, CBM_VERSION);- snprintf(stored_path, sizeof(stored_path), "%s/cbm-integrations.json", stored_dir);+ ASSERT_TRUE(cbm_integration_assets_ownership_path(tmpdir, stored_path, sizeof(stored_path)));+ snprintf(stored_dir, sizeof(stored_dir), "%s", stored_path);+ char *stored_separator = strrchr(stored_dir, '/');+ ASSERT_NOT_NULL(stored_separator);+ *stored_separator = '\0';char *saved_assets = save_test_env("CBM_ASSETS_DIR");cbm_unsetenv("CBM_ASSETS_DIR");@@ -9746,12 +10441,149 @@ TEST(cli_integration_assets_install_stores_versioned_ownership_copy) {if (!dry_ok || !dry_wrote_nothing)FAIL("a dry-run install must verify but write no stored copy");if (!install_ok || !stored_exists)- FAIL("install must persist the verified asset copy under ~/.cbm/assets/<version>/");+ FAIL("install must persist the verified asset copy under ~/.cbm/assets/<sha256>/");if (!stored_verifies)FAIL("the stored copy must re-verify against the embedded hash");PASS();}+/* The old ownership-copy publisher opened the predictable `<stored>.tmp`+ * pathname with fopen(), followed a precreated symlink, overwrote the foreign+ * target, and then renamed the symlink into place. Transaction staging must+ * use an exclusively-created unpredictable sibling and leave that foreign+ * pathname byte-for-byte untouched. */+TEST(cli_integration_assets_install_never_follows_predictable_temp_symlink) {+#ifdef _WIN32+ SKIP_PLATFORM("Windows reparse-point creation requires privileges");+#else+ static const char sentinel_bytes[] = "foreign integration temp sentinel\n";+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-assets-temp-sentinel-XXXXXX");+ if (!cbm_mkdtemp(tmpdir))+ FAIL("cbm_mkdtemp failed");+ char stored_dir[512];+ char stored_path[640];+ char predictable_temp[672];+ char sentinel_path[512];+ ASSERT_TRUE(cbm_integration_assets_ownership_path(tmpdir, stored_path, sizeof(stored_path)));+ snprintf(stored_dir, sizeof(stored_dir), "%s", stored_path);+ char *stored_separator = strrchr(stored_dir, '/');+ ASSERT_NOT_NULL(stored_separator);+ *stored_separator = '\0';+ snprintf(predictable_temp, sizeof(predictable_temp), "%s.tmp", stored_path);+ snprintf(sentinel_path, sizeof(sentinel_path), "%s/foreign-sentinel", tmpdir);+ test_mkdirp(stored_dir);+ write_test_file(sentinel_path, sentinel_bytes);+ ASSERT_EQ(symlink(sentinel_path, predictable_temp), 0);++ char *saved_assets = save_test_env("CBM_ASSETS_DIR");+ cbm_unsetenv("CBM_ASSETS_DIR");+ cbm_integration_assets_reset_for_testing();+ char err[512] = {0};+ bool installed = cbm_integration_assets_install(tmpdir, false, err, sizeof(err));++ char *sentinel_after = read_test_file_alloc(sentinel_path);+ struct stat temp_info;+ bool foreign_link_preserved =+ lstat(predictable_temp, &temp_info) == 0 && S_ISLNK(temp_info.st_mode);+ char *stored = read_test_file_alloc(stored_path);+ bool stored_exists = stored != NULL;+ bool sentinel_preserved = sentinel_after && strcmp(sentinel_after, sentinel_bytes) == 0;+ free(sentinel_after);+ free(stored);++ restore_test_env("CBM_ASSETS_DIR", saved_assets);+ cbm_integration_assets_reset_for_testing();+ test_rmdir_r(tmpdir);+ ASSERT_TRUE(installed);+ ASSERT_TRUE(stored_exists);+ ASSERT_TRUE(foreign_link_preserved);+ ASSERT_TRUE(sentinel_preserved);+ PASS();+#endif+}++/* Rechecking a pathname before commit is insufficient: an attacker with an+ * already-open writable handle can change bytes without changing the inode.+ * Integration publication validates the public target after rename; removal+ * first moves the object to a private retained name and validates that exact+ * object before deletion. */+TEST(cli_integration_asset_commits_reject_in_place_rewrite_after_stage) {+ char tmpdir[256];+ snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-assets-commit-XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmpdir));+ char install_dir[512];+ char adjacent_path[640];+ snprintf(install_dir, sizeof(install_dir), "%s/bin", tmpdir);+ snprintf(adjacent_path, sizeof(adjacent_path), "%s/%s", install_dir,+ CBM_INTEGRATIONS_ASSET_NAME);++ char *saved_assets = save_test_env("CBM_ASSETS_DIR");+ ASSERT_EQ(cbm_setenv("CBM_ASSETS_DIR", "assets", 1), 0);+ cbm_integration_assets_reset_for_testing();+ char error[512] = {0};++ cbm_activation_transaction_t *adjacent = NULL;+ cbm_activation_transaction_t *ownership = NULL;+ ASSERT_TRUE(cbm_integration_assets_stage_install(tmpdir, install_dir, &adjacent, &ownership,+ error, sizeof(error)));+ ASSERT_NOT_NULL(adjacent);+ ASSERT_NOT_NULL(ownership);+ const char *staged = cbm_activation_transaction_staged_path(adjacent);+ ASSERT_NOT_NULL(staged);+ FILE *staged_file = cbm_fopen(staged, "r+b");+ ASSERT_NOT_NULL(staged_file);+ ASSERT_EQ(fseek(staged_file, -1L, SEEK_END), 0);+ int staged_last = fgetc(staged_file);+ ASSERT_TRUE(staged_last != EOF);+ ASSERT_EQ(fseek(staged_file, -1L, SEEK_END), 0);+ ASSERT_TRUE(fputc(staged_last ^ 1, staged_file) != EOF);+ ASSERT_EQ(fclose(staged_file), 0);+ ASSERT_EQ(cbm_integration_assets_commit_install(adjacent),+ CBM_ACTIVATION_TRANSACTION_VALIDATION_FAILED);+ ASSERT_EQ(cbm_activation_transaction_close(&adjacent), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_activation_transaction_close(&ownership), CBM_ACTIVATION_TRANSACTION_OK);+ cbm_path_info_t path_info;+ ASSERT_TRUE(cbm_path_info_utf8(adjacent_path, &path_info) != 0);++ ASSERT_TRUE(cbm_integration_assets_stage_install(tmpdir, install_dir, &adjacent, &ownership,+ error, sizeof(error)));+ ASSERT_EQ(cbm_integration_assets_commit_install(adjacent), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_integration_assets_commit_install(ownership), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_activation_transaction_finalize(adjacent), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_activation_transaction_finalize(ownership), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_activation_transaction_close(&adjacent), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_activation_transaction_close(&ownership), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_TRUE(cbm_integration_assets_verify_file(adjacent_path));++ bool foreign = false;+ ASSERT_TRUE(cbm_integration_assets_stage_remove(tmpdir, install_dir, &adjacent, &ownership,+ &foreign, error, sizeof(error)));+ ASSERT_FALSE(foreign);+ ASSERT_NOT_NULL(adjacent);+ ASSERT_NOT_NULL(ownership);+ FILE *target_file = cbm_fopen(adjacent_path, "r+b");+ ASSERT_NOT_NULL(target_file);+ ASSERT_EQ(fseek(target_file, -1L, SEEK_END), 0);+ int target_last = fgetc(target_file);+ ASSERT_TRUE(target_last != EOF);+ ASSERT_EQ(fseek(target_file, -1L, SEEK_END), 0);+ ASSERT_TRUE(fputc(target_last ^ 1, target_file) != EOF);+ ASSERT_EQ(fclose(target_file), 0);+ ASSERT_EQ(cbm_integration_assets_commit_removal(adjacent),+ CBM_ACTIVATION_TRANSACTION_VALIDATION_FAILED);+ ASSERT_EQ(cbm_activation_transaction_close(&adjacent), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_activation_transaction_close(&ownership), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_path_info_utf8(adjacent_path, &path_info), 0);+ ASSERT_TRUE(path_info.is_regular);+ ASSERT_FALSE(cbm_integration_assets_verify_file(adjacent_path));++ restore_test_env("CBM_ASSETS_DIR", saved_assets);+ cbm_integration_assets_reset_for_testing();+ test_rmdir_r(tmpdir);+ PASS();+}+/* Pin the CURRENT posix gate body byte-for-byte. Every already-deployed* install holds files with exactly these bytes; a well-meaning edit to the* template in cbm-integrations.json would silently turn them all foreign@@ -9932,8 +10764,14 @@ TEST(cli_uninstall_removes_claude_hook_scripts) {#endifcbm_install_agent_configs(tmpdir, binary, false, false);+ cli_activation_fake_t fake = {+ .mutation_reserve_result = 1,+ };+ cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake);+ cbm_cli_set_activation_ops_for_test(&ops);char *args[] = {"-n"};int rc = cli_test_cmd_uninstall(1, args);+ cbm_cli_set_activation_ops_for_test(NULL);#ifdef _WIN32const char *const names[] = {"cbm-code-discovery-gate.cmd",@@ -9993,8 +10831,14 @@ TEST(cli_uninstall_preserves_modified_claude_hook_script) {snprintf(modified_path, sizeof(modified_path), "%s/hooks/cbm-session-reminder", config_dir);const char *sentinel = "#!/bin/sh\necho user-modified-session-hook\n";write_test_file(modified_path, sentinel);+ cli_activation_fake_t fake = {+ .mutation_reserve_result = 1,+ };+ cbm_cli_activation_ops_t ops = cli_activation_fake_ops(&fake);+ cbm_cli_set_activation_ops_for_test(&ops);char *args[] = {"-n"};(void)cli_test_cmd_uninstall(1, args);+ cbm_cli_set_activation_ops_for_test(NULL);char *after = read_test_file_alloc(modified_path);bool preserved = after && strcmp(after, sentinel) == 0;free(after);@@ -12126,12 +12970,41 @@ TEST(cli_sha256_file_matches_known_vector) {PASS();}+/* RFC 4231 section 4.2, test case 1. The daemon/UI readiness handshake uses+ * this standard construction; binding it independently prevents two matching+ * implementation mistakes from authenticating one another. */+TEST(cli_hmac_sha256_matches_rfc4231_vector) {+ uint8_t key[20];+ memset(key, 0x0b, sizeof(key));+ static const char data[] = "Hi There";+ static const uint8_t expected[CBM_SHA256_DIGEST_LEN] = {+ 0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf,+ 0xce, 0xaf, 0x0b, 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83,+ 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7,+ };+ uint8_t actual[CBM_SHA256_DIGEST_LEN];+ cbm_hmac_sha256(key, sizeof(key), data, sizeof(data) - 1U, actual);+ ASSERT_MEM_EQ(actual, expected, sizeof(expected));+ PASS();+}++TEST(cli_secure_zero_overwrites_sensitive_storage) {+ uint8_t sensitive[CBM_SHA256_DIGEST_LEN];+ memset(sensitive, 0xa5, sizeof(sensitive));+ cbm_secure_zero(sensitive, sizeof(sensitive));+ for (size_t index = 0; index < sizeof(sensitive); index++) {+ ASSERT_EQ(sensitive[index], 0U);+ }+ PASS();+}+#ifdef _WIN32/* The Windows update contract, asserted with the activation seam OFF so this* takes the exact dispatch a release binary ships: `update` never replaces the* running image in-process (Windows locks it), it prints the install.ps1- * command and exits 0. Regressing to an in-process self-update would mean- * reintroducing the launcher stub Defender flags as Trojan:Win32/Wacatac.B!ml. */+ * command and exits 0. Regressing to an in-process self-update would restore a+ * second verifier/launcher executable and the dual-use replacement capability+ * deliberately removed from the release architecture. */TEST(cli_windows_update_hands_off_to_install_script) {char tmpdir[256];snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-update-handoff-XXXXXX");@@ -12143,7 +13016,10 @@ TEST(cli_windows_update_hands_off_to_install_script) {cli_activation_save_env(&old_home, &old_cache);cbm_setenv("HOME", tmpdir, 1);char cache_dir[512];+ char runtime_parent[512];snprintf(cache_dir, sizeof(cache_dir), "%s/cache", tmpdir);+ snprintf(runtime_parent, sizeof(runtime_parent), "%s/runtime", tmpdir);+ test_mkdirp(runtime_parent);cbm_setenv("CBM_CACHE_DIR", cache_dir, 1);char bin_dir[512];@@ -12154,7 +13030,11 @@ TEST(cli_windows_update_hands_off_to_install_script) {write_test_file(bin_target, "in-process update must not touch this");char *update_argv[] = {"--yes"};+ /* Keep the seam disabled, but contain any regressed in-process activation+ * to this fixture instead of the developer's account-global daemon. */+ cbm_cli_set_activation_runtime_parent_for_test(runtime_parent);int update_rc = cbm_cmd_update(1, update_argv);+ cbm_cli_set_activation_runtime_parent_for_test(NULL);const char *installed = read_test_file(bin_target);bool preserved = installed && strcmp(installed, "in-process update must not touch this") == 0;@@ -12178,6 +13058,9 @@ SUITE(cli) {RUN_TEST(cli_progress_sink_accepts_worker_json_logs);RUN_TEST(cli_progress_sink_serializes_concurrent_callbacks);RUN_TEST(cli_sha256_file_matches_known_vector);+ RUN_TEST(cli_hmac_sha256_matches_rfc4231_vector);+ RUN_TEST(cli_secure_zero_overwrites_sensitive_storage);+ RUN_TEST(cli_command_fixtures_isolate_activation_from_live_account);RUN_TEST(cli_checksum_manifest_requires_exact_filename_and_accepts_star);RUN_TEST(cli_checksum_manifest_rejects_invalid_missing_and_conflicting_digest);RUN_TEST(cli_checksum_manifest_rejects_oversized_input);@@ -12198,12 +13081,18 @@ SUITE(cli) {RUN_TEST(cli_install_reset_deletion_waits_for_final_activation_guard);RUN_TEST(cli_install_config_only_waits_for_cohort_drain);RUN_TEST(cli_install_config_and_path_finish_before_guard_release);- RUN_TEST(cli_install_config_failure_keeps_published_binary);+ RUN_TEST(cli_install_config_failure_restores_previous_runtime_set);+ RUN_TEST(cli_install_gc_is_guarded_content_bound_and_after_binary_publish);+#ifndef _WIN32+ RUN_TEST(cli_concurrent_ui_then_standard_install_leaves_coherent_standard_set);+#endifRUN_TEST(cli_update_download_failure_does_not_quiesce_sessions);RUN_TEST(cli_update_already_current_does_not_quiesce_sessions);RUN_TEST(cli_update_agent_configs_finish_before_guard_release);RUN_TEST(cli_uninstall_quiesces_active_cohort_before_removing_binary_and_index);RUN_TEST(cli_uninstall_preserves_binary_and_index_when_cohort_does_not_drain);+ RUN_TEST(cli_uninstall_custom_dir_removes_exact_owned_runtime_set);+ RUN_TEST(cli_uninstall_preserves_foreign_integration_sidecar);RUN_TEST(cli_activation_guard_is_bypassed_for_dry_run_and_plan);#ifdef _WIN32RUN_TEST(cli_windows_update_hands_off_to_install_script);@@ -12422,7 +13311,10 @@ SUITE(cli) {RUN_TEST(cli_upgrade_migrates_released_claude_hook_scripts);RUN_TEST(cli_upgrade_preserves_near_legacy_claude_hook_script);RUN_TEST(cli_integration_assets_tampered_or_missing_fail_closed);- RUN_TEST(cli_integration_assets_install_stores_versioned_ownership_copy);+ RUN_TEST(cli_runtime_asset_probe_requires_exact_adjacent_set);+ RUN_TEST(cli_integration_assets_install_stores_content_addressed_ownership_copy);+ RUN_TEST(cli_integration_assets_install_never_follows_predictable_temp_symlink);+ RUN_TEST(cli_integration_asset_commits_reject_in_place_rewrite_after_stage);RUN_TEST(cli_integration_current_gate_script_bytes_are_pinned);RUN_TEST(cli_hook_upsert_rejects_linked_settings);RUN_TEST(cli_claude_hook_script_collisions_are_not_registered);diff --git a/tests/test_daemon_application.c b/tests/test_daemon_application.cindex 5ad262a3f..c639ace2f 100644--- a/tests/test_daemon_application.c+++ b/tests/test_daemon_application.c@@ -13,6 +13,7 @@#include "foundation/compat_fs.h"#include "foundation/compat_thread.h"#include "foundation/platform.h"+#include "foundation/sha256.h"#include "foundation/subprocess.h"#include "mcp/mcp.h"#include "mcp/mcp_internal.h"@@ -515,6 +516,145 @@ TEST(daemon_application_ui_config_rejects_noncanonical_frames) {PASS();}+TEST(daemon_application_ui_readiness_proof_is_generation_bound_before_context) {+ uint8_t first_secret[CBM_SHA256_DIGEST_LEN];+ uint8_t second_secret[CBM_SHA256_DIGEST_LEN];+ uint8_t request[1U + CBM_SHA256_DIGEST_LEN];+ for (size_t index = 0; index < CBM_SHA256_DIGEST_LEN; index++) {+ first_secret[index] = (uint8_t)index;+ second_secret[index] = (uint8_t)(index + 1U);+ request[index + 1U] = (uint8_t)(index + 32U);+ }+ request[0] = CBM_DAEMON_APPLICATION_REQUEST_UI_READINESS_PROOF;+ static const uint8_t expected_first[CBM_SHA256_DIGEST_LEN] = {+ 0x62, 0x21, 0x5d, 0xe7, 0xbd, 0xdc, 0xea, 0x7e, 0x2c, 0x40, 0x47,+ 0xff, 0x6b, 0xb9, 0x4f, 0x8d, 0x18, 0x26, 0x2f, 0xc8, 0xb3, 0xf3,+ 0x64, 0x81, 0x34, 0xbb, 0x7d, 0x44, 0x15, 0x8f, 0xf8, 0x4d,+ };+ static const uint8_t expected_second[CBM_SHA256_DIGEST_LEN] = {+ 0xe3, 0xb0, 0x69, 0x53, 0x9c, 0x19, 0xc2, 0x2d, 0x3f, 0x6d, 0x34,+ 0x60, 0x67, 0x86, 0x15, 0x78, 0xbe, 0xa9, 0xc4, 0xb9, 0xe4, 0x61,+ 0xcb, 0xf9, 0xb8, 0x06, 0xad, 0x1b, 0xcd, 0x64, 0xa4, 0x81,+ };++ cbm_daemon_application_config_t first_config = {+ .ui_readiness_secret = first_secret,+ .ui_readiness_secret_length = sizeof(first_secret),+ };+ cbm_daemon_application_config_t second_config = {+ .ui_readiness_secret = second_secret,+ .ui_readiness_secret_length = sizeof(second_secret),+ };+ cbm_daemon_application_t *first = cbm_daemon_application_new(&first_config);+ cbm_daemon_application_t *second = cbm_daemon_application_new(&second_config);+ cbm_daemon_application_t *without_secret = cbm_daemon_application_new(NULL);+ cbm_daemon_application_config_t malformed_config = {+ .ui_readiness_secret = first_secret,+ .ui_readiness_secret_length = sizeof(first_secret) - 1U,+ };+ cbm_daemon_application_t *malformed = cbm_daemon_application_new(&malformed_config);++ cbm_daemon_runtime_application_callbacks_t first_callbacks =+ cbm_daemon_application_runtime_callbacks(first);+ cbm_daemon_runtime_application_callbacks_t second_callbacks =+ cbm_daemon_application_runtime_callbacks(second);+ cbm_daemon_runtime_application_callbacks_t no_secret_callbacks =+ cbm_daemon_application_runtime_callbacks(without_secret);+ cbm_daemon_runtime_application_session_t *first_session =+ first ? app_test_open(&first_callbacks, 304) : NULL;+ cbm_daemon_runtime_application_session_t *second_session =+ second ? app_test_open(&second_callbacks, 305) : NULL;+ cbm_daemon_runtime_application_session_t *no_secret_session =+ without_secret ? app_test_open(&no_secret_callbacks, 306) : NULL;++ uint8_t *first_response = NULL;+ uint32_t first_length = 0;+ cbm_daemon_runtime_application_status_t first_status =+ first_session ? app_test_request(&first_callbacks, first_session, request, sizeof(request),+ &first_response, &first_length)+ : CBM_DAEMON_RUNTIME_APPLICATION_TRANSPORT_ERROR;+ uint8_t *second_response = NULL;+ uint32_t second_length = 0;+ cbm_daemon_runtime_application_status_t second_status =+ second_session ? app_test_request(&second_callbacks, second_session, request,+ sizeof(request), &second_response, &second_length)+ : CBM_DAEMON_RUNTIME_APPLICATION_TRANSPORT_ERROR;+ uint8_t *malformed_response = NULL;+ uint32_t malformed_length = 0;+ cbm_daemon_runtime_application_status_t short_status =+ first_session+ ? app_test_request(&first_callbacks, first_session, request, sizeof(request) - 1U,+ &malformed_response, &malformed_length)+ : CBM_DAEMON_RUNTIME_APPLICATION_TRANSPORT_ERROR;+ free(malformed_response);+ malformed_response = NULL;+ malformed_length = 0;+ uint8_t long_request[2U + CBM_SHA256_DIGEST_LEN];+ memcpy(long_request, request, sizeof(request));+ long_request[sizeof(long_request) - 1U] = 0;+ cbm_daemon_runtime_application_status_t long_status =+ first_session+ ? app_test_request(&first_callbacks, first_session, long_request, sizeof(long_request),+ &malformed_response, &malformed_length)+ : CBM_DAEMON_RUNTIME_APPLICATION_TRANSPORT_ERROR;+ free(malformed_response);+ malformed_response = NULL;+ malformed_length = 0;+ cbm_daemon_runtime_application_status_t no_secret_status =+ no_secret_session+ ? app_test_request(&no_secret_callbacks, no_secret_session, request, sizeof(request),+ &malformed_response, &malformed_length)+ : CBM_DAEMON_RUNTIME_APPLICATION_TRANSPORT_ERROR;+ free(malformed_response);++ if (first_session) {+ first_callbacks.session_close(first_callbacks.context, first_session);+ }+ if (second_session) {+ second_callbacks.session_close(second_callbacks.context, second_session);+ }+ if (no_secret_session) {+ no_secret_callbacks.session_close(no_secret_callbacks.context, no_secret_session);+ }+ bool first_stopped = first && cbm_daemon_application_shutdown(first, APP_TEST_TIMEOUT_MS);+ bool second_stopped = second && cbm_daemon_application_shutdown(second, APP_TEST_TIMEOUT_MS);+ bool no_secret_stopped =+ without_secret && cbm_daemon_application_shutdown(without_secret, APP_TEST_TIMEOUT_MS);+ bool malformed_rejected = malformed == NULL;+ bool first_exact = first_response && first_length == sizeof(expected_first) &&+ memcmp(first_response, expected_first, sizeof(expected_first)) == 0;+ bool second_exact = second_response && second_length == sizeof(expected_second) &&+ memcmp(second_response, expected_second, sizeof(expected_second)) == 0;+ bool generations_differ = first_response && second_response &&+ memcmp(first_response, second_response, CBM_SHA256_DIGEST_LEN) != 0;+ cbm_daemon_application_free(first);+ cbm_daemon_application_free(second);+ cbm_daemon_application_free(without_secret);+ cbm_daemon_application_free(malformed);+ free(first_response);+ free(second_response);++ ASSERT_NOT_NULL(first);+ ASSERT_NOT_NULL(second);+ ASSERT_NOT_NULL(without_secret);+ ASSERT_TRUE(malformed_rejected);+ ASSERT_NOT_NULL(first_session);+ ASSERT_NOT_NULL(second_session);+ ASSERT_NOT_NULL(no_secret_session);+ ASSERT_EQ(first_status, CBM_DAEMON_RUNTIME_APPLICATION_OK);+ ASSERT_TRUE(first_exact);+ ASSERT_EQ(second_status, CBM_DAEMON_RUNTIME_APPLICATION_OK);+ ASSERT_TRUE(second_exact);+ ASSERT_TRUE(generations_differ);+ ASSERT_EQ(short_status, CBM_DAEMON_RUNTIME_APPLICATION_REJECTED);+ ASSERT_EQ(long_status, CBM_DAEMON_RUNTIME_APPLICATION_REJECTED);+ ASSERT_EQ(no_secret_status, CBM_DAEMON_RUNTIME_APPLICATION_REJECTED);+ ASSERT_TRUE(first_stopped);+ ASSERT_TRUE(second_stopped);+ ASSERT_TRUE(no_secret_stopped);+ PASS();+}+TEST(daemon_application_requires_immutable_explicit_context) {cbm_daemon_application_t *application = cbm_daemon_application_new(NULL);cbm_daemon_runtime_application_callbacks_t callbacks =@@ -4949,6 +5089,7 @@ SUITE(daemon_application) {RUN_TEST(daemon_application_requires_immutable_explicit_context);RUN_TEST(daemon_application_ui_config_updates_are_masked_and_serialized);RUN_TEST(daemon_application_ui_config_rejects_noncanonical_frames);+ RUN_TEST(daemon_application_ui_readiness_proof_is_generation_bound_before_context);RUN_TEST(daemon_application_restricted_profile_owns_no_background_surfaces);RUN_TEST(daemon_application_hook_context_preserves_event_and_dialect);RUN_TEST(daemon_application_mcp_notification_has_no_response);diff --git a/tests/test_daemon_bootstrap.c b/tests/test_daemon_bootstrap.cindex d0e557a03..f898db5f2 100644--- a/tests/test_daemon_bootstrap.c+++ b/tests/test_daemon_bootstrap.c@@ -284,11 +284,13 @@ TEST(daemon_bootstrap_classifies_stateless_commands_without_client) {char *install[] = {"codebase-memory-mcp", "install", "--dry-run", NULL};char *uninstall[] = {"codebase-memory-mcp", "uninstall", NULL};char *update[] = {"codebase-memory-mcp", "update", "-n", NULL};+ char *verify_runtime_assets[] = {"codebase-memory-mcp", "--verify-runtime-assets", NULL};ASSERT_EQ(classify(2, version), CBM_DAEMON_PROCESS_STATELESS);ASSERT_EQ(classify(3, help), CBM_DAEMON_PROCESS_STATELESS);ASSERT_EQ(classify(3, install), CBM_DAEMON_PROCESS_STATELESS);ASSERT_EQ(classify(2, uninstall), CBM_DAEMON_PROCESS_STATELESS);ASSERT_EQ(classify(3, update), CBM_DAEMON_PROCESS_STATELESS);+ ASSERT_EQ(classify(2, verify_runtime_assets), CBM_DAEMON_PROCESS_STATELESS);ASSERT_FALSE(cbm_daemon_process_role_requires_client(CBM_DAEMON_PROCESS_STATELESS));PASS();}diff --git a/tests/test_daemon_open_readiness.py b/tests/test_daemon_open_readiness.pynew file mode 100644index 000000000..bffce810d--- /dev/null+++ b/tests/test_daemon_open_readiness.py@@ -0,0 +1,402 @@+r"""Product guard for ``daemon start --open`` UI readiness.++The daemon intentionally warms and verifies its external UI pack after the+control socket is already available. ``--open`` is the one synchronous user+request in that flow: it must wait for the *CBM HTTP endpoint*, not merely for+the daemon process, before it reports or opens the URL.++This guard uses a real UI build and isolated daemon generations:++* a temporarily occupied port proves the command waits and then succeeds once+ the verified UI listener becomes available;+* a foreign service returning the exact formerly accepted HTML markers proves+ public page text is not treated as daemon identity;+* a copied binary without its content-addressed pack proves missing/invalid+ runtime assets never result in an opened or reported UI URL.+* a second ``daemon start --open`` proves the already-active daemon path obtains+ the same generation-bound proof over a fresh authenticated IPC client.++Build the fixture with test seams so browser launching is recorded rather than+performed and the two negative cases can use a short deterministic deadline:++ make -f Makefile.cbm cbm-with-ui TEST_SEAMS=1 BUILD_DIR=build/ui-open-test+ python3 tests/test_daemon_open_readiness.py build/ui-open-test/codebase-memory-mcp++Exit code: 0 == green, 1 == behavior regression, 2 == fixture/setup error.+"""++import os+import re+import shutil+import socket+import stat+import subprocess+import sys+import tempfile+import threading+import time+++OPEN_MARKER_ENV = "CBM_TEST_DAEMON_OPEN_MARKER"+READY_TIMEOUT_ENV = "CBM_TEST_DAEMON_UI_READY_TIMEOUT_MS"+RUNTIME_PARENT_ENV = "CBM_TEST_DAEMON_RUNTIME_PARENT"+++def output_text(result):+ return ((result.stdout or b"") + (result.stderr or b"")).decode("utf-8", "replace")+++def pid_from(text):+ match = re.search(r"pid[: ]+(\d+)", text)+ return int(match.group(1)) if match else 0+++def force_kill(pid):+ if not pid:+ return+ if os.name == "nt":+ subprocess.run(["taskkill", "/F", "/PID", str(pid)], capture_output=True, timeout=30)+ else:+ subprocess.run(["kill", "-9", str(pid)], capture_output=True, timeout=30)+++def stop_daemon(binary, env, pid):+ stopped = False+ try:+ subprocess.run([binary, "daemon", "stop"], capture_output=True, timeout=30, env=env)+ except (OSError, subprocess.TimeoutExpired):+ pass+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ try:+ status = subprocess.run([binary, "daemon", "status"], capture_output=True,+ timeout=2, env=env)+ if status.returncode != 0 and "not running" in output_text(status):+ stopped = True+ break+ except (OSError, subprocess.TimeoutExpired):+ pass+ time.sleep(0.1)+ if not stopped:+ force_kill(pid)+++def occupied_loopback_port():+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ if os.name != "nt":+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ listener.bind(("127.0.0.1", 0))+ listener.listen(16)+ return listener, listener.getsockname()[1]+++class OldMarkerResponder:+ """Foreign HTTP service that exactly matches the former acceptance rule."""++ BODY = b"<!doctype html><html><head><title>Codebase Memory</title></head></html>"++ def __init__(self):+ self.listener, self.port = occupied_loopback_port()+ self.listener.settimeout(0.1)+ self.stop_event = threading.Event()+ self.request_count = 0+ self.thread = threading.Thread(target=self._serve, name="old-marker-responder",+ daemon=True)+ self.thread.start()++ def _serve(self):+ response = (+ b"HTTP/1.1 200 OK\r\n"+ b"Content-Type: text/html; charset=utf-8\r\n"+ b"Cache-Control: no-cache\r\n"+ b"Content-Length: " + str(len(self.BODY)).encode("ascii") + b"\r\n"+ b"Connection: close\r\n\r\n" + self.BODY+ )+ while not self.stop_event.is_set():+ try:+ connection, _ = self.listener.accept()+ except socket.timeout:+ continue+ except OSError:+ break+ try:+ connection.settimeout(0.5)+ self.request_count += 1+ try:+ connection.recv(4096)+ except (OSError, socket.timeout):+ pass+ connection.sendall(response)+ except OSError:+ pass+ finally:+ connection.close()++ def close(self):+ self.stop_event.set()+ self.listener.close()+ self.thread.join(timeout=2)+++def fixture_environment(work, cache, marker, timeout_ms):+ env = dict(os.environ)+ env["CBM_CACHE_DIR"] = cache+ env[OPEN_MARKER_ENV] = marker+ env[READY_TIMEOUT_ENV] = str(timeout_ms)+ runtime_parent = os.path.join(work, "runtime-" + os.path.basename(cache))+ os.makedirs(runtime_parent, mode=0o700, exist_ok=True)+ env[RUNTIME_PARENT_ENV] = runtime_parent+ env["CBM_TEST_FAKE_BROWSER_MARKER"] = marker++ # Before the production fix exists, POSIX builds do not know the marker+ # seam. A PATH-local opener lets the very same behavior test demonstrate+ # the original premature-open RED instead of failing during setup.+ if os.name != "nt":+ fake_bin = os.path.join(work, "fake-bin")+ os.makedirs(fake_bin, exist_ok=True)+ opener = "open" if sys.platform == "darwin" else "xdg-open"+ opener_path = os.path.join(fake_bin, opener)+ if not os.path.exists(opener_path):+ with open(opener_path, "w", encoding="utf-8", newline="\n") as handle:+ handle.write("#!/bin/sh\nprintf '%s' \"$1\" > \"$CBM_TEST_FAKE_BROWSER_MARKER\"\n")+ os.chmod(opener_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)+ env["PATH"] = fake_bin + os.pathsep + env.get("PATH", "")+ return env+++def launch_start(binary, work, cache, marker, port, timeout_ms):+ os.makedirs(cache, exist_ok=True)+ env = fixture_environment(work, cache, marker, timeout_ms)+ process = subprocess.Popen(+ [binary, "daemon", "start", "--port=%d" % port, "--open"],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ env=env,+ )+ return process, env+++def collect(process, timeout=30):+ stdout, stderr = process.communicate(timeout=timeout)+ result = subprocess.CompletedProcess(process.args, process.returncode, stdout, stderr)+ return result, output_text(result)+++def wait_daemon_active(binary, env, process, timeout=10):+ deadline = time.monotonic() + timeout+ last_probe = "status probe was not attempted"+ while time.monotonic() < deadline:+ if process.poll() is not None:+ return False+ try:+ status = subprocess.run([binary, "daemon", "status"], capture_output=True,+ timeout=2, env=env)+ last_probe = "status rc=%d: %s" % (status.returncode, output_text(status)[:600])+ except subprocess.TimeoutExpired as timeout_error:+ # The starter may still own the short bootstrap handoff. A timed+ # status probe is not evidence either way; retry within this+ # function's independent bounded deadline.+ partial = (timeout_error.stdout or b"") + (timeout_error.stderr or b"")+ last_probe = "status timed out: %s" % partial.decode("utf-8", "replace")[:600]+ continue+ if status.returncode == 0 and "daemon: active" in output_text(status):+ return True+ time.sleep(0.1)+ print("diagnostic: %s" % last_probe)+ return False+++def assert_delayed_success(binary, work):+ cache = os.path.join(work, "cache-delayed")+ marker = os.path.join(work, "browser-delayed.txt")+ blocker, port = occupied_loopback_port()+ process, env = launch_start(binary, work, cache, marker, port, 10000)+ daemon_pid = 0+ try:+ if not wait_daemon_active(binary, env, process):+ result, text = collect(process)+ daemon_pid = pid_from(text)+ print("RED: daemon control service never became active during --open:\n%s"+ % text[:600])+ return False+ # Generic daemon readiness is explicitly not UI readiness. Once status+ # is active, leave enough time for the buggy command to report/open;+ # the fixed command remains blocked on the authenticated HTTP probe.+ time.sleep(0.4)+ if process.poll() is not None or os.path.exists(marker):+ result, text = collect(process)+ daemon_pid = pid_from(text)+ print("RED: --open returned/opened while another listener still owned the UI port:\n%s"+ % text[:600])+ return False++ # The daemon's first bind failed without delaying its control service.+ # Releasing the port lets the background retry publish the real CBM UI.+ blocker.close()+ blocker = None+ result, text = collect(process, timeout=25)+ daemon_pid = pid_from(text)+ expected_url = "http://127.0.0.1:%d" % port+ marker_text = ""+ if os.path.exists(marker):+ with open(marker, "r", encoding="utf-8") as handle:+ marker_text = handle.read()+ if result.returncode != 0 or expected_url not in text or marker_text != expected_url:+ print("RED: --open did not wait through the background UI retry and then open the "+ "verified endpoint:\n%s\nmarker=%r" % (text[:700], marker_text))+ return False+ print("PASS: --open waited for the verified UI endpoint before reporting/opening it")+ return True+ finally:+ if blocker is not None:+ blocker.close()+ if process.poll() is None:+ process.kill()+ _, text = collect(process)+ daemon_pid = daemon_pid or pid_from(text)+ stop_daemon(binary, env, daemon_pid)+++def assert_bounded_foreign_port_failure(binary, work):+ cache = os.path.join(work, "cache-occupied")+ marker = os.path.join(work, "browser-occupied.txt")+ blocker = OldMarkerResponder()+ port = blocker.port+ process, env = launch_start(binary, work, cache, marker, port, 900)+ daemon_pid = 0+ try:+ result, text = collect(process, timeout=10)+ daemon_pid = pid_from(text)+ url = "http://127.0.0.1:%d" % port+ if (result.returncode == 0 or os.path.exists(marker) or url in text or+ "UI endpoint did not become ready" not in text or "--port" not in text):+ print("RED: --open must reject a bounded wait on a foreign/occupied endpoint "+ "without reporting or opening its URL:\n%s" % text[:700])+ return False+ request_count = blocker.request_count+ status = subprocess.run([binary, "daemon", "status"], capture_output=True,+ timeout=3, env=env)+ status_text = output_text(status)+ if (status.returncode != 0 or "daemon: active" not in status_text or+ blocker.request_count != request_count):+ print("RED: daemon status must remain a bounded control-plane probe and must not "+ "contact a configured foreign HTTP listener:\n%s\nrequests=%d->%d" %+ (status_text[:700], request_count, blocker.request_count))+ return False+ print("PASS: exact legacy HTML markers cannot spoof daemon-generation readiness")+ return True+ finally:+ blocker.close()+ if process.poll() is None:+ process.kill()+ _, text = collect(process)+ daemon_pid = daemon_pid or pid_from(text)+ stop_daemon(binary, env, daemon_pid)+++def assert_active_daemon_open(binary, work):+ cache = os.path.join(work, "cache-active")+ marker = os.path.join(work, "browser-active.txt")+ probe, port = occupied_loopback_port()+ probe.close()+ os.makedirs(cache, exist_ok=True)+ env = fixture_environment(work, cache, marker, 10000)+ daemon_pid = 0+ try:+ first = subprocess.run([binary, "daemon", "start", "--port=%d" % port],+ capture_output=True, timeout=30, env=env)+ first_text = output_text(first)+ daemon_pid = pid_from(first_text)+ if first.returncode != 0 or "daemon: started" not in first_text:+ print("RED: initial asynchronous daemon start failed:\n%s" % first_text[:700])+ return False++ second = subprocess.run([binary, "daemon", "start", "--open"], capture_output=True,+ timeout=20, env=env)+ second_text = output_text(second)+ expected_url = "http://127.0.0.1:%d" % port+ marker_text = ""+ if os.path.exists(marker):+ with open(marker, "r", encoding="utf-8") as handle:+ marker_text = handle.read()+ if (second.returncode != 0 or "daemon: already active" not in second_text or+ expected_url not in second_text or marker_text != expected_url):+ print("RED: active-daemon --open did not authenticate and open its exact "+ "generation:\n%s\nmarker=%r" % (second_text[:700], marker_text))+ return False+ print("PASS: an already-active daemon is opened only after generation-bound proof")+ return True+ finally:+ stop_daemon(binary, env, daemon_pid)+++def assert_missing_pack_failure(binary, work):+ isolated = os.path.join(work, "without-pack")+ os.makedirs(isolated, exist_ok=True)+ copied_binary = os.path.join(isolated, os.path.basename(binary))+ shutil.copy2(binary, copied_binary)++ cache = os.path.join(work, "cache-missing-pack")+ marker = os.path.join(work, "browser-missing-pack.txt")+ probe, port = occupied_loopback_port()+ probe.close() # reserve an unused port number without keeping it occupied+ process, env = launch_start(copied_binary, work, cache, marker, port, 900)+ daemon_pid = 0+ try:+ result, text = collect(process, timeout=10)+ daemon_pid = pid_from(text)+ url = "http://127.0.0.1:%d" % port+ if (result.returncode == 0 or os.path.exists(marker) or url in text or+ "UI endpoint did not become ready" not in text or+ "matching runtime assets" not in text):+ print("RED: a UI binary without its verified pack must fail --open without "+ "reporting/opening a URL:\n%s" % text[:700])+ return False+ print("PASS: missing verified UI assets fail --open without opening/reporting a URL")+ return True+ finally:+ if process.poll() is None:+ process.kill()+ _, text = collect(process)+ daemon_pid = daemon_pid or pid_from(text)+ stop_daemon(copied_binary, env, daemon_pid)+++def main():+ if len(sys.argv) != 2:+ print("usage: python3 test_daemon_open_readiness.py <ui-binary>")+ return 2+ binary = os.path.abspath(sys.argv[1])+ if not os.path.isfile(binary):+ print("SETUP FAIL: binary not found: %s" % binary)+ return 2+ binary_dir = os.path.dirname(binary)+ if not any(name.startswith("cbm-ui-") and name.endswith(".pack")+ for name in os.listdir(binary_dir)):+ print("SETUP FAIL: no cbm-ui-*.pack adjacent to UI binary: %s" % binary_dir)+ return 2+ if os.name == "nt":+ with open(binary, "rb") as handle:+ if OPEN_MARKER_ENV.encode("ascii") not in handle.read():+ print("SETUP FAIL: Windows fixture must be built with TEST_SEAMS=1")+ return 2++ # macOS sockaddr_un paths are capped at 104 bytes. Anchor the isolated+ # runtime directly under /private/tmp rather than the much longer per-user+ # Darwin temporary root so the product endpoint itself remains valid.+ short_temp_root = "/private/tmp" if sys.platform == "darwin" else tempfile.gettempdir()+ with tempfile.TemporaryDirectory(prefix="cbm_uiopen_", dir=short_temp_root) as work:+ if not assert_delayed_success(binary, work):+ return 1+ if not assert_bounded_foreign_port_failure(binary, work):+ return 1+ if not assert_active_daemon_open(binary, work):+ return 1+ if not assert_missing_pack_failure(binary, work):+ return 1+ print("\nGREEN: daemon --open is bound to verified UI endpoint readiness.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/test_daemon_runtime.c b/tests/test_daemon_runtime.cindex 4fe055fd9..c97c5ad18 100644--- a/tests/test_daemon_runtime.c+++ b/tests/test_daemon_runtime.c@@ -246,7 +246,7 @@ static bool runtime_test_windows_copy_self(const char *destination) {wchar_t source[32768];DWORD source_length =GetModuleFileNameW(NULL, source, (DWORD)(sizeof(source) / sizeof(source[0])));- wchar_t *destination_wide = cbm_utf8_to_wide(destination);+ wchar_t *destination_wide = cbm_path_to_wide(destination);bool copied = source_length > 0 &&source_length < (DWORD)(sizeof(source) / sizeof(source[0])) && destination_wide &&CopyFileW(source, destination_wide, TRUE) != 0;@@ -314,7 +314,7 @@ static bool runtime_test_windows_spawn_image_holder(const char *image_path, conschar command_line[RUNTIME_TEST_PATH_CAP * 2];int written = snprintf(command_line, sizeof(command_line),"\"%s\" __cbm_runtime_image_holder \"%s\"", image_path, ready_event);- wchar_t *application = cbm_utf8_to_wide(image_path);+ wchar_t *application = cbm_path_to_wide(image_path);wchar_t *command =written > 0 && written < (int)sizeof(command_line) ? cbm_utf8_to_wide(command_line) : NULL;STARTUPINFOW startup;@@ -4151,6 +4151,108 @@ TEST(daemon_runtime_kernel_process_fingerprint_is_stable_and_fail_closed) {PASS();}+#ifdef _WIN32+TEST(daemon_runtime_process_fingerprint_supports_extended_length_image) {+ static const char segment[] = "/segment-abcdefghijklmnopqrstuvwxyz-0123456789";+ char root[RUNTIME_TEST_PATH_CAP] = {0};+ char directory[RUNTIME_TEST_PATH_CAP] = {0};+ char image_path[RUNTIME_TEST_PATH_CAP] = {0};+ char event_name[128] = {0};+ int root_written =+ snprintf(root, sizeof(root), "%s/cbm-runtime-long-image-XXXXXX", cbm_tmpdir());+ bool root_created =+ root_written > 0 && root_written < (int)sizeof(root) && cbm_mkdtemp(root) != NULL;+ bool path_built = root_created && snprintf(directory, sizeof(directory), "%s", root) > 0;+ for (size_t index = 0; path_built && index < 7U; index++) {+ size_t used = strlen(directory);+ int appended = snprintf(directory + used, sizeof(directory) - used, "%s", segment);+ path_built = appended > 0 && (size_t)appended < sizeof(directory) - used;+ }+ bool directory_created = path_built && cbm_mkdir_p(directory, 0700);+ int image_written = directory_created ? snprintf(image_path, sizeof(image_path),+ "%s/test-runner-long-image.exe", directory)+ : -1;+ wchar_t *ordinary_wide = image_written > 0 && image_written < (int)sizeof(image_path)+ ? cbm_utf8_to_wide(image_path)+ : NULL;+ bool exceeds_legacy_limit = ordinary_wide && wcslen(ordinary_wide) >= MAX_PATH;+ free(ordinary_wide);+ bool copied = exceeds_legacy_limit && runtime_test_windows_copy_self(image_path);+ const char *expected = runtime_test_self_build();++ int event_written =+ snprintf(event_name, sizeof(event_name), "Local\\cbm-runtime-long-image-%lu-%llu",+ (unsigned long)GetCurrentProcessId(), (unsigned long long)GetTickCount64());+ HANDLE ready_event = copied && expected && expected[0] && event_written > 0 &&+ event_written < (int)sizeof(event_name)+ ? CreateEventA(NULL, TRUE, FALSE, event_name)+ : NULL;+ bool event_private = ready_event && GetLastError() != ERROR_ALREADY_EXISTS;+ PROCESS_INFORMATION process;+ memset(&process, 0, sizeof(process));+ bool spawned =+ event_private && runtime_test_windows_spawn_image_holder(image_path, event_name, &process);+ bool ready = spawned && WaitForSingleObject(ready_event, 5000U) == WAIT_OBJECT_0;++ wchar_t process_path[32768];+ DWORD process_path_length = (DWORD)(sizeof(process_path) / sizeof(process_path[0]));+ bool queried_long_image =+ ready &&+ QueryFullProcessImageNameW(process.hProcess, 0U, process_path, &process_path_length) != 0 &&+ process_path_length >= MAX_PATH;+ char observed[CBM_DAEMON_BUILD_FINGERPRINT_SIZE] = {0};+ bool fingerprinted = queried_long_image && cbm_daemon_runtime_process_build_fingerprint(+ (uint64_t)process.dwProcessId, observed);+ bool exact = fingerprinted && strcmp(observed, expected) == 0;++ bool stopped = !spawned;+ if (spawned) {+ bool termination_requested = TerminateProcess(process.hProcess, 30U) != 0;+ stopped =+ termination_requested && WaitForSingleObject(process.hProcess, 5000U) == WAIT_OBJECT_0;+ (void)CloseHandle(process.hProcess);+ }+ if (ready_event) {+ (void)CloseHandle(ready_event);+ }+ bool image_removed = !copied || cbm_unlink(image_path) == 0;+ bool tree_removed = true;+ if (root_created) {+ char cleanup[RUNTIME_TEST_PATH_CAP];+ (void)snprintf(cleanup, sizeof(cleanup), "%s", directory_created ? directory : root);+ for (;;) {+ tree_removed = cbm_rmdir(cleanup) == 0 && tree_removed;+ if (strcmp(cleanup, root) == 0) {+ break;+ }+ char *separator = strrchr(cleanup, '/');+ if (!separator || separator < cleanup + strlen(root)) {+ tree_removed = false;+ break;+ }+ *separator = '\0';+ }+ }++ ASSERT_TRUE(root_created);+ ASSERT_TRUE(path_built);+ ASSERT_TRUE(directory_created);+ ASSERT_TRUE(exceeds_legacy_limit);+ ASSERT_TRUE(copied);+ ASSERT_TRUE(runtime_test_is_fingerprint(expected));+ ASSERT_TRUE(event_private);+ ASSERT_TRUE(spawned);+ ASSERT_TRUE(ready);+ ASSERT_TRUE(queried_long_image);+ ASSERT_TRUE(fingerprinted);+ ASSERT_TRUE(exact);+ ASSERT_TRUE(stopped);+ ASSERT_TRUE(image_removed);+ ASSERT_TRUE(tree_removed);+ PASS();+}+#endif+#ifdef __APPLE__/* RED: the former macOS fast path accepted the daemon vnode in any RX mapping,* even when a differently fingerprinted main executable owned the connection.@@ -4604,6 +4706,9 @@ SUITE(daemon_runtime) {RUN_TEST(daemon_host_forced_shutdown_is_logged_flushed_and_process_bounded);#endifRUN_TEST(daemon_runtime_kernel_process_fingerprint_is_stable_and_fail_closed);+#ifdef _WIN32+ RUN_TEST(daemon_runtime_process_fingerprint_supports_extended_length_image);+#endif#ifdef __APPLE__RUN_TEST(daemon_runtime_mac_fast_path_rejects_foreign_main_image_mapping_active);#endifdiff --git a/tests/test_httpd.c b/tests/test_httpd.cindex e3a3dc080..137a725f1 100644--- a/tests/test_httpd.c+++ b/tests/test_httpd.c@@ -778,6 +778,69 @@ static bool ui_adr_equals(const ui_delete_fixture_t *fx, const char *project,return equal;}+TEST(ui_server_readiness_proof_is_exact_and_generation_bound) {+ static const char challenge[] =+ "202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f";+ static const char expected[] =+ "62215de7bddcea7e2c4047ff6bb94f8d18262fc8b3f3648134bb7d44158ff84d";+ uint8_t secret[CBM_SHA256_DIGEST_LEN];+ for (size_t index = 0; index < sizeof(secret); index++) {+ secret[index] = (uint8_t)index;+ }++ th_server_t without_secret;+ ASSERT_EQ(th_server_start(&without_secret), 0);+ char request[512];+ ASSERT_GT(snprintf(request, sizeof(request),+ "GET /__cbm/ui-readiness?challenge=%s HTTP/1.1\r\n\r\n", challenge),+ 0);+ char response[4096];+ int response_length =+ th_http(cbm_http_server_port(without_secret.srv), request, response, sizeof(response));+ int missing_secret_status = response_length > 0 ? th_status(response) : -1;+ th_server_stop(&without_secret);++ th_server_t server = {0};+ server.srv = cbm_http_server_new(0);+ ASSERT_NOT_NULL(server.srv);+ cbm_http_server_set_readiness_secret(server.srv, secret);+ ASSERT_EQ(th_server_thread_start(&server.tid, server.srv), 0);+ int port = cbm_http_server_port(server.srv);+ response_length = th_http(port, request, response, sizeof(response));+ char *body = response_length > 0 ? strstr(response, "\r\n\r\n") : NULL;+ body = body ? body + 4 : NULL;+ bool exact_proof = response_length > 0 && th_status(response) == 200 && body &&+ strcmp(body, expected) == 0 &&+ strstr(response, "Content-Type: text/plain; charset=utf-8") != NULL &&+ strstr(response, "Cache-Control: no-store") != NULL;++ ASSERT_GT(snprintf(request, sizeof(request),+ "GET /__cbm/ui-readiness?challenge="+ "202122232425262728292A2b2c2d2e2f303132333435363738393a3b3c3d3e3f "+ "HTTP/1.1\r\n\r\n"),+ 0);+ response_length = th_http(port, request, response, sizeof(response));+ int uppercase_status = response_length > 0 ? th_status(response) : -1;++ ASSERT_GT(snprintf(request, sizeof(request),+ "GET /__cbm/ui-readiness?challenge=%s&extra=1 HTTP/1.1\r\n\r\n", challenge),+ 0);+ response_length = th_http(port, request, response, sizeof(response));+ int extra_parameter_status = response_length > 0 ? th_status(response) : -1;++ response_length =+ th_http(port, "GET /__cbm/ui-readiness HTTP/1.1\r\n\r\n", response, sizeof(response));+ int missing_challenge_status = response_length > 0 ? th_status(response) : -1;+ th_server_stop(&server);++ ASSERT_EQ(missing_secret_status, 503);+ ASSERT_TRUE(exact_proof);+ ASSERT_EQ(uppercase_status, 400);+ ASSERT_EQ(extra_parameter_status, 400);+ ASSERT_EQ(missing_challenge_status, 400);+ PASS();+}+TEST(ui_server_unknown_path_404) {th_server_t ts;ASSERT_EQ(th_server_start(&ts), 0);@@ -899,15 +962,17 @@ TEST(ui_server_free_never_joins_active_index_worker) {PASS();}-TEST(ui_server_root_serves_stub_404) {- /* Test binary links embedded_stub.c → no frontend → 404 with marker */+TEST(ui_server_root_without_ready_assets_is_retryable) {+ /* A listener should normally be gated on READY by the daemon. Direct+ * constructor tests still receive a truthful retryable response. */th_server_t ts;ASSERT_EQ(th_server_start(&ts), 0);char resp[4096];int n = th_http(cbm_http_server_port(ts.srv), "GET / HTTP/1.1\r\n\r\n", resp, sizeof(resp));ASSERT_GT(n, 0);- ASSERT_EQ(th_status(resp), 404);- ASSERT_NOT_NULL(strstr(resp, "no frontend embedded"));+ ASSERT_EQ(th_status(resp), 503);+ ASSERT_NOT_NULL(strstr(resp, "frontend assets are not ready"));+ ASSERT_NOT_NULL(strstr(resp, "Retry-After: 1"));th_server_stop(&ts);PASS();}@@ -2060,8 +2125,8 @@ TEST(ui_server_logs_escape_dense_no_overflow) {}char req[256];int port = cbm_http_server_port(ts.srv);- snprintf(req, sizeof(req),- "GET /api/logs?lines=500 HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n", port);+ snprintf(req, sizeof(req), "GET /api/logs?lines=500 HTTP/1.1\r\nHost: 127.0.0.1:%d\r\n\r\n",+ port);size_t cap = 4u * 1024u * 1024u;char *resp = malloc(cap);int n = resp ? th_http(port, req, resp, (int)cap) : 0;@@ -2219,12 +2284,13 @@ SUITE(httpd) {RUN_TEST(httpd_close_refuses_while_connection_owns_listener);/* Full UI server */+ RUN_TEST(ui_server_readiness_proof_is_exact_and_generation_bound);RUN_TEST(ui_server_rejects_non_loopback_host);RUN_TEST(ui_server_unknown_path_404);RUN_TEST(ui_server_process_kill_route_is_unavailable);RUN_TEST(ui_server_routes_indexing_through_joinable_daemon_executor);RUN_TEST(ui_server_free_never_joins_active_index_worker);- RUN_TEST(ui_server_root_serves_stub_404);+ RUN_TEST(ui_server_root_without_ready_assets_is_retryable);RUN_TEST(ui_server_same_origin_request_is_allowed);RUN_TEST(ui_server_rejects_foreign_and_null_origins);RUN_TEST(ui_server_mutations_require_json_content_type);diff --git a/tests/test_main.c b/tests/test_main.cindex a46ec8338..120c036b2 100644--- a/tests/test_main.c+++ b/tests/test_main.c@@ -998,7 +998,7 @@ int main(int argc, char **argv) {RUN_SELECTED_SUITE(slab_alloc);RUN_SELECTED_SUITE(mem);- /* UI (config, embedded assets, layout) */+ /* UI (config, external asset pack, layout) */RUN_SELECTED_SUITE(ui);/* UI HTTP server (transport + routing) */diff --git a/tests/test_no_embedded_scripts_contract.sh b/tests/test_no_embedded_scripts_contract.shindex 0baf389bc..52b3db5c3 100644--- a/tests/test_no_embedded_scripts_contract.sh+++ b/tests/test_no_embedded_scripts_contract.sh@@ -1,11 +1,12 @@#!/usr/bin/env bash-# Contract: the product must not embed integration-script text.+# Contract: the native product must not embed integration or frontend bytes.## The binary used to carry nine complete shebang'd shell scripts, their# PowerShell/.cmd twins and the node:child_process client modules as C string# literals — written to client config dirs at 0755. A block of script-shaped-# bytes inside an unsigned executable is exactly the surface Microsoft-# Defender's ML scored as Trojan:Script/Wacatac.B!ml. Those bodies now live in+# bytes inside a native executable is unnecessary mixed-content with plausible+# static-classifier overlap. That is a risk-reduction rationale, not feature+# attribution for an opaque vendor verdict. Those bodies now live in# assets/cbm-integrations.json (hash-verified; the binary embeds only the# SHA-256), and this contract is the proof the removal STAYS removed: one# revived string literal would silently hand the next release its@@ -16,10 +17,10 @@# node:child_process literal. Absence at source level makes absence a# BUILD property of every artifact (standard, ui, all platforms) — not a# reachability assumption about any one binary.-# 2. ARTIFACT: when build/c/codebase-memory-mcp exists, its bytes are-# scanned directly. scripts/ci/check-binary-composition.sh (A6) runs the-# same needles on every RELEASE artifact post-strip, so a missing local-# build here skips only a redundant leg, never the property.+# 2. ARTIFACT: when build/c/codebase-memory-mcp exists, its bytes are scanned+# directly. scripts/ci/check-binary-composition.sh runs the script needles+# on every release variant (A6 and A7), so a+# missing local build here skips only a redundant leg, never the property.## Comment stripping is mandatory, not tidiness: a contract that a COMMENT can# satisfy (or trip) is a false guard — see test_spawn_no_window_contract.sh,@@ -100,16 +101,82 @@ for must_scan in ("src/cli/cli.c", "src/cli/client_adapter.c"):failures.append(f"{must_scan} is gone — re-point this contract at the ""file that now owns integration installs")+# The release gate must enforce UI script absence unconditionally and preserve+# the native-vs-pack byte boundary. A debug environment escape hatch here would+# make the source assertion true while shipped UI binaries quietly bypass it.+composition = (root / "scripts/ci/check-binary-composition.sh").read_text(+ encoding="utf-8", errors="replace"+)+if "CBM_CHECK_UI_SCRIPTS_ABSENT" in composition:+ failures.append("binary composition gate still permits UI script-scan bypass")+for required in ("A6-no-embedded-scripts", "A7-no-ui-asset-bytes", "CBMUIPK",+ "<!doctype html>", '<script type="module" crossorigin'):+ if required not in composition:+ failures.append(f"binary composition gate is missing {required!r}")+a7 = composition.split("# A7 —", 1)+if len(a7) != 2:+ failures.append("binary composition gate has no A7 implementation")+else:+ a7_body = a7[1].split("\n}", 1)[0]+ if 'if [ "$is_ui"' in a7_body:+ failures.append("A7 raw frontend-byte check is conditional on UI path classification")+ if 'for needle in "${UI_ASSET_BYTE_NEEDLES[@]}"' not in a7_body:+ failures.append("A7 does not scan every native artifact for every frontend-byte needle")++# Filename-selected abort/busy-loop injectors are useful only in deterministic+# supervisor tests. They must be compiled out of ordinary production builds,+# while the broad source-matrix smoke explicitly opts into them so coverage is+# preserved rather than silently deleted.+cbm_source = (root / "internal/cbm/cbm.c").read_text(+ encoding="utf-8", errors="replace"+)+if "#ifdef CBM_ENABLE_TEST_SEAMS\n/* Deterministic supervisor fault injection" not in cbm_source:+ failures.append("internal crash/hang fault injector is not behind CBM_ENABLE_TEST_SEAMS")+if "#ifdef CBM_ENABLE_TEST_SEAMS\n cbm_test_fault_inject(rel_path);\n#endif" not in cbm_source:+ failures.append("fault-injector call site is not behind CBM_ENABLE_TEST_SEAMS")+for needle in ("CBM_TEST_CRASH_ON", "CBM_TEST_HANG_ON"):+ if needle not in composition.split("SEAM_NEEDLES=(", 1)[-1].split(")", 1)[0]:+ failures.append(f"binary composition gate does not forbid {needle}")+smoke_workflow = (root / ".github/workflows/smoke.yml").read_text(+ encoding="utf-8", errors="replace"+)+if smoke_workflow.count("TEST_SEAMS=1") != 3:+ failures.append("wide smoke matrix must opt into test seams on all three build jobs")++# Standard production must not acquire the parser's pack/file-I/O surface just+# because tests need it. One stub substitution keeps each link topology exact:+# standard = no-I/O stub; UI = real parser + generated manifest; test/repro/TSan+# = real parser + empty manifest. Linking either manifest twice is an error.+makefile = (root / "Makefile.cbm").read_text(encoding="utf-8", errors="replace")+for required in (+ "src/ui/asset_pack_stub.c",+ "TEST_PROD_SRCS = $(subst src/ui/asset_pack_stub.c,src/ui/asset_pack.c "+ "src/ui/asset_manifest_stub.c,$(PROD_SRCS))",+ "PROD_SRCS_WITH_ASSETS = $(subst src/ui/asset_pack_stub.c,src/ui/asset_pack.c "+ "$(UI_ASSET_MANIFEST),$(PROD_SRCS))",+):+ if required not in makefile:+ failures.append(f"Makefile UI link topology is missing {required!r}")+ui_sources = makefile.split("UI_SRCS =", 1)[-1].split("# mimalloc", 1)[0]+for forbidden in ("src/ui/asset_pack.c", "src/ui/asset_manifest_stub.c"):+ if forbidden in ui_sources:+ failures.append(f"standard UI_SRCS still links {forbidden}")+for target in ("test-runner", "test-repro-runner", "test-runner-tsan"):+ rule = makefile.split(f"$(BUILD_DIR)/{target}:", 1)+ if len(rule) != 2 or "$(TEST_PROD_SRCS)" not in rule[1].split("\n\n", 1)[0]:+ failures.append(f"{target} does not link the full parser test source set")+if scanned == 0:print("FAIL: scanned no production sources — this contract checks nothing")sys.exit(1)if failures:- print(f"FAIL: {len(failures)} embedded script literal(s) in production sources:\n")+ print(f"FAIL: {len(failures)} native-image byte-boundary violation(s):\n")for f in failures:print(f" - {f}")print("\nIntegration bodies belong in assets/cbm-integrations.json (verified by "- "the embedded SHA-256), never in the binary. A justified exception needs "+ "the embedded SHA-256), and frontend bytes belong in the verified UI pack, "+ "never in the binary. A justified exception needs ""an ALLOWLIST entry in this file.")sys.exit(1)@@ -127,9 +194,11 @@ if [ ! -f "$BINARY" ]; thenfifail=0-for needle in '#!/usr/bin/env bash' '#!/bin/bash' '#!/bin/sh' 'node:child_process'; do+for needle in '#!/usr/bin/env bash' '#!/bin/bash' '#!/bin/sh' 'node:child_process' \+ 'CBMUIPK' '<!doctype html>' '<html lang="en" class="dark">' \+ '<script type="module" crossorigin'; doif LC_ALL=C grep -a -q -F -e "$needle" "$BINARY"; then- echo "FAIL: built binary contains '$needle' — an integration body is embedded again"+ echo "FAIL: built binary contains '$needle' — sidecar bytes are embedded again"fail=1fidone@@ -139,5 +208,5 @@ if ! LC_ALL=C grep -a -q -F -e 'codebase-memory-mcp' "$BINARY"; thenecho "FAIL: canary string missing — $BINARY is not a readable product binary"fail=1fi-[ "$fail" -eq 0 ] && echo "OK: built binary carries no shebang or node:child_process bytes"+[ "$fail" -eq 0 ] && echo "OK: built binary carries no integration scripts or raw UI-pack bytes"exit "$fail"diff --git a/tests/test_package_runtime_assets_contract.sh b/tests/test_package_runtime_assets_contract.shnew file mode 100644index 000000000..04446f82c--- /dev/null+++ b/tests/test_package_runtime_assets_contract.sh@@ -0,0 +1,506 @@+#!/usr/bin/env bash+# Runtime-sidecar contract for release archives, package managers and source+# installers. Release packaging executes the final staged binary against the+# exact adjacent files it will archive; downstream packages must retain those+# files either beside the executable or in ../share/codebase-memory-mcp.+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"++python3 - "$ROOT" <<'PY'+from __future__ import annotations++import json+import hashlib+import os+import pathlib+import platform+import re+import shlex+import struct+import subprocess+import sys+import tarfile+import tempfile+import zipfile+++root = pathlib.Path(sys.argv[1])+failures: list[str] = []+++def read(relative: str) -> str:+ return (root / relative).read_text(encoding="utf-8")+++def require(condition: bool, message: str) -> None:+ if not condition:+ failures.append(message)+++package_release = read("scripts/package-release.sh")+strip_position = package_release.find('strip_release_binary "$STAGED_BINARY"')+probe_position = package_release.find('"$STAGED_BINARY" --verify-runtime-assets')+tar_position = package_release.find('tar -czf "$OUT_DIR/$NAME.tar.gz"')+zip_position = package_release.find('zip -q "$OUT_DIR/$NAME.zip"')+require(+ 'if ! "$STAGED_BINARY" --verify-runtime-assets; then' in package_release,+ "release packaging must execute the final staged binary's runtime-asset probe",+)+require(+ min(strip_position, probe_position, tar_position, zip_position) >= 0+ and strip_position < probe_position < tar_position+ and probe_position < zip_position,+ "Unix release packaging must probe after final binary transformation and before archive",+)+require(+ re.search(+ r'tar\s+-czf\s+"\$OUT_DIR/\$NAME\.tar\.gz"\s+-C\s+"\$PACK_DIR"',+ package_release,+ )+ is not None,+ "Unix release archive must be created from the same private directory that was probed",+)+require(+ 'cd "$PACK_DIR"' in package_release+ and 'zip -q "$OUT_DIR/$NAME.zip" "${ARCHIVE_MEMBERS[@]}"' in package_release,+ "Windows release archive must be created from the same private directory that was probed",+)+++homebrew = read("pkg/homebrew/Formula/codebase-memory-mcp.rb")+require(+ re.search(+ r'\(share\s*/\s*["\']codebase-memory-mcp["\']\)\.install\s+'+ r'["\']cbm-integrations\.json["\']',+ homebrew,+ )+ is not None,+ "Homebrew must install cbm-integrations.json in ../share/codebase-memory-mcp",+)+require(+ re.search(+ r'assert_path_exists\s+share\s*/\s*["\']codebase-memory-mcp/'+ r'cbm-integrations\.json["\']',+ homebrew,+ )+ is not None,+ "Homebrew formula test must assert the installed integration asset",+)+require(+ "codebase-memory-mcp install" in homebrew,+ "Homebrew must retain the opt-in agent-configuration caveat",+)++aur = read("pkg/aur/PKGBUILD")+require(+ re.search(+ r'install\s+-Dm644\s+["\']\$\{srcdir\}/cbm-integrations\.json["\']'+ r'\s*\\?\s*["\']\$\{pkgdir\}/usr/share/codebase-memory-mcp/'+ r'cbm-integrations\.json["\']',+ aur,+ )+ is not None,+ "AUR must install cbm-integrations.json in /usr/share/codebase-memory-mcp",+)++scoop = json.loads(read("pkg/scoop/codebase-memory-mcp.json"))+scoop_post_install = scoop.get("post_install", [])+if isinstance(scoop_post_install, str):+ scoop_post_install = [scoop_post_install]+require(+ not any(re.search(r'\binstall(?:\s|$)', command, re.IGNORECASE)+ for command in scoop_post_install),+ "Scoop must not invoke the full native install command after extracting the package",+)+require(+ scoop["architecture"]["64bit"].get("bin") == "codebase-memory-mcp.exe",+ "Scoop shim must target the executable inside the extracted package directory",+)++choco_install = read("pkg/chocolatey/tools/chocolateyInstall.ps1")+choco_uninstall = read("pkg/chocolatey/tools/chocolateyUninstall.ps1")+require(+ re.search(r'&\s*\$binPath\s+install\b', choco_install, re.IGNORECASE) is None,+ "Chocolatey must not invoke the full native install command after extraction",+)+require(+ re.search(r'-UnzipLocation\s+\$installDir\b', choco_install) is not None+ and re.search(+ r'\$binPath\s*=\s*Join-Path\s+\$installDir\s+'+ r'["\']codebase-memory-mcp\.exe["\']',+ choco_install,+ re.IGNORECASE,+ )+ is not None,+ "Chocolatey must shim the executable in the whole extracted package directory",+)+require(+ re.search(r'Remove-Item\s+\$installDir\s+-Recurse\s+-Force', choco_uninstall) is not None,+ "Chocolatey uninstall must remove the package-owned extraction directory",+)++setup_sh = read("scripts/setup.sh")+asset_helper = setup_sh.split("install_integration_asset() {", 1)[-1].split(+ "download_binary() {", 1+)[0]+download_body = setup_sh.split("download_binary() {", 1)[-1].split(+ "# --- Build from source ---", 1+)[0]+source_body = setup_sh.split("build_from_source() {", 1)[-1].split(+ "# --- MCP auto-configuration ---", 1+)[0]+require(+ re.search(+ r'cp\s+["\']\$source_path["\']\s+'+ r'["\']\$\{INSTALL_DIR\}/cbm-integrations\.json["\']',+ asset_helper,+ )+ is not None,+ "Unix integration-asset helper must copy the JSON beside the binary",+)+require(+ 'install_integration_asset "$tmpdir"' in download_body,+ "Unix release download must install cbm-integrations.json beside the binary",+)+require(+ 'install_integration_asset "${SOURCE_DIR}/build/c"' in source_body,+ "Unix source build must install cbm-integrations.json beside the binary",+)++setup_windows = read("scripts/setup-windows.ps1")+windows_source = setup_windows.split("if ($FromSource) {", 1)[-1].split(+ "} else {", 1+)[0]+windows_download = setup_windows.split("} else {", 1)[-1]+require(+ re.search(+ r'cp\s+build/c/codebase-memory-mcp\s+build/c/cbm-integrations\.json\s+'+ r'/home/\$wslUser/\.local/bin/',+ windows_source,+ )+ is not None,+ "Windows source build must copy cbm-integrations.json beside the WSL binary",+)+require(+ re.search(+ r'Expand-Archive\s+-Path\s+\$tmpZip\s+-DestinationPath\s+\$InstallDir\s+-Force',+ windows_download,+ re.IGNORECASE,+ )+ is not None,+ "Windows release download must retain the complete archive in the install directory",+)++glama = read("pkg/glama/Dockerfile")+require(+ re.search(r'tar\s+-xz\s+-C\s+/tmp[^\n]*cbm-integrations\.json', glama) is not None,+ "Glama package extraction must retain cbm-integrations.json",+)+require(+ re.search(+ r'COPY\s+--from=fetch\s+/tmp/cbm-integrations\.json\s+'+ r'/usr/local/share/codebase-memory-mcp/cbm-integrations\.json',+ glama,+ )+ is not None,+ "Glama must install cbm-integrations.json at the executable-relative share path",+)+++# Exercise the packager itself with a tiny native executable that implements+# the same hidden command-line contract as the product. This is deliberately a+# native fixture (rather than a shell script): package-release still has to run+# its real strip and binary-composition gates before it reaches the association+# probe. The two negative cases distinguish self-integrity from association:+# the alternate UI pack is structurally valid and named by its own SHA-256, but+# it is not the pack the staged binary declares; likewise, the repository JSON+# is a valid manifest but is not the manifest expected by the mismatch fixture.+fixture_source_template = r'''+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#define EXPECT_INTEGRATION __EXPECT_INTEGRATION__+#define EXPECT_UI_NAME __EXPECT_UI_NAME__+#define EXPECT_UI_MARKER __EXPECT_UI_MARKER__++static int file_contains(const char *path, const char *needle) {+ FILE *stream = fopen(path, "rb");+ if (!stream) return 0;+ const size_t needle_length = strlen(needle);+ size_t matched = 0;+ int byte = 0;+ while (needle_length > 0 && (byte = fgetc(stream)) != EOF) {+ if ((unsigned char)byte == (unsigned char)needle[matched]) {+ matched++;+ if (matched == needle_length) {+ fclose(stream);+ return 1;+ }+ } else {+ matched = ((unsigned char)byte == (unsigned char)needle[0]) ? 1U : 0U;+ }+ }+ fclose(stream);+ return 0;+}++static int adjacent_path(const char *argv0, const char *leaf, char *out, size_t out_size) {+ char directory[4096];+ const size_t length = strlen(argv0);+ if (length == 0 || length >= sizeof(directory)) return 0;+ memcpy(directory, argv0, length + 1U);+ char *slash = strrchr(directory, '/');+ char *backslash = strrchr(directory, '\\');+ if (backslash && (!slash || backslash > slash)) slash = backslash;+ if (!slash) return 0;+ *slash = '\0';+ const int written = snprintf(out, out_size, "%s/%s", directory, leaf);+ return written > 0 && (size_t)written < out_size;+}++int main(int argc, char **argv) {+ static const char product[] = "codebase-memory-mcp";+ char path[4096];+ if (argc != 2 || strcmp(argv[1], "--verify-runtime-assets") != 0) {+ fprintf(stderr, "%s fixture accepts only the runtime-asset probe\n", product);+ return 64;+ }+ if (!adjacent_path(argv[0], "cbm-integrations.json", path, sizeof(path)) ||+ !file_contains(path, EXPECT_INTEGRATION)) {+ fprintf(stderr, "%s fixture rejected integration assets\n", product);+ return 65;+ }+ if (EXPECT_UI_NAME[0] != '\0' &&+ (!adjacent_path(argv[0], EXPECT_UI_NAME, path, sizeof(path)) ||+ !file_contains(path, EXPECT_UI_MARKER))) {+ fprintf(stderr, "%s fixture rejected UI assets\n", product);+ return 66;+ }+ return 0;+}+'''+++def valid_ui_pack(marker: str) -> bytes:+ path = b"/index.html"+ payload = ("<title>" + marker + "</title>").encode("ascii")+ header = bytearray(80)+ header[:8] = b"CBMUIPK\0"+ struct.pack_into("<HHIII", header, 8, 1, 80, 0, 1, 24)+ paths_offset = 80 + 24+ payload_offset = paths_offset + len(path)+ total = payload_offset + len(payload)+ struct.pack_into(+ "<QQQQQQQ",+ header,+ 24,+ 80,+ 24,+ paths_offset,+ len(path),+ payload_offset,+ len(payload),+ total,+ )+ entry = struct.pack("<IHBBQQ", 0, len(path), 1, 1, 0, len(payload))+ return bytes(header) + entry + path + payload+++host_system = platform.system().lower()+host_is_windows = (+ os.name == "nt"+ or bool(os.environ.get("MSYSTEM"))+ or host_system.startswith(("windows", "msys", "mingw", "cygwin"))+)+host_goos = "windows" if host_is_windows else (+ "darwin" if host_system == "darwin" else "linux"+)+binary_name = "codebase-memory-mcp.exe" if host_goos == "windows" else "codebase-memory-mcp"+archive_suffix = ".zip" if host_goos == "windows" else ".tar.gz"+compiler = shlex.split(os.environ.get("CC", "cc"))+arch_flags = shlex.split(os.environ.get("ARCHFLAGS", ""))+integration_marker = '\"format\":1,\"product\":\"codebase-memory-mcp\"'+pack_a = valid_ui_pack("fixture-pack-a")+pack_b = valid_ui_pack("fixture-pack-b")+pack_a_digest = hashlib.sha256(pack_a).hexdigest()+pack_b_digest = hashlib.sha256(pack_b).hexdigest()+pack_a_name = f"cbm-ui-{pack_a_digest}.pack"+pack_b_name = f"cbm-ui-{pack_b_digest}.pack"+++def build_fixture(+ directory: pathlib.Path,+ expected_integration: str,+ expected_ui_name: str = "",+ expected_ui_marker: str = "",+) -> None:+ source = fixture_source_template+ source = source.replace("__EXPECT_INTEGRATION__", json.dumps(expected_integration))+ source = source.replace("__EXPECT_UI_NAME__", json.dumps(expected_ui_name))+ source = source.replace("__EXPECT_UI_MARKER__", json.dumps(expected_ui_marker))+ source_path = directory / "runtime_asset_fixture.c"+ source_path.write_text(source, encoding="utf-8")+ command = compiler + arch_flags + ["-std=c11", "-O2", str(source_path)]+ if host_goos == "linux":+ command.append("-Wl,-z,noexecstack")+ command += ["-o", str(directory / binary_name)]+ compiled = subprocess.run(+ command,+ cwd=root,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ check=False,+ )+ require(+ compiled.returncode == 0,+ "could not compile native release-packaging fixture: " + compiled.stdout.strip(),+ )+++def package_fixture(+ work: pathlib.Path,+ case: str,+ variant: str,+ expected_integration: str,+ pack_name: str = "",+ pack_bytes: bytes = b"",+ expected_ui_name: str = "",+ expected_ui_marker: str = "",+) -> tuple[subprocess.CompletedProcess[str], pathlib.Path]:+ build_dir = work / f"{case}-build"+ output_dir = work / f"{case}-output"+ build_dir.mkdir()+ output_dir.mkdir()+ build_fixture(build_dir, expected_integration, expected_ui_name, expected_ui_marker)+ if pack_name:+ (build_dir / pack_name).write_bytes(pack_bytes)+ environment = os.environ.copy()+ environment["BUILD_DIR"] = str(build_dir)+ archive_name = f"codebase-memory-mcp{'-ui' if variant == 'ui' else ''}-{host_goos}-fixture{archive_suffix}"+ packaged = subprocess.run(+ [+ "bash",+ str(root / "scripts/package-release.sh"),+ host_goos,+ "fixture",+ "--variant",+ variant,+ "--out-dir",+ str(output_dir),+ ],+ cwd=root,+ env=environment,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ check=False,+ )+ return packaged, output_dir / archive_name+++if compiler:+ with tempfile.TemporaryDirectory(prefix="cbm-package-association-") as temp:+ work = pathlib.Path(temp)+ standard, standard_archive = package_fixture(+ work, "standard-ok", "standard", integration_marker+ )+ require(+ standard.returncode == 0 and standard_archive.is_file(),+ "release packager rejected a matching standard fixture: " + standard.stdout.strip(),+ )+ if standard_archive.is_file():+ if host_goos == "windows":+ with zipfile.ZipFile(standard_archive) as archive:+ standard_members = set(archive.namelist())+ else:+ with tarfile.open(standard_archive, "r:gz") as archive:+ standard_members = set(archive.getnames())+ require(+ standard_members+ == {+ binary_name,+ "cbm-integrations.json",+ "LICENSE",+ "install.ps1" if host_goos == "windows" else "install.sh",+ "THIRD_PARTY_NOTICES.md",+ },+ "standard archive must contain exactly the five verified/staged members "+ f"(got {sorted(standard_members)!r})",+ )++ ui, ui_archive = package_fixture(+ work,+ "ui-ok",+ "ui",+ integration_marker,+ pack_a_name,+ pack_a,+ pack_a_name,+ "fixture-pack-a",+ )+ require(+ ui.returncode == 0 and ui_archive.is_file(),+ "release packager rejected a matching UI fixture: " + ui.stdout.strip(),+ )+ if ui_archive.is_file():+ if host_goos == "windows":+ with zipfile.ZipFile(ui_archive) as archive:+ ui_members = set(archive.namelist())+ else:+ with tarfile.open(ui_archive, "r:gz") as archive:+ ui_members = set(archive.getnames())+ require(+ ui_members+ == {+ binary_name,+ "cbm-integrations.json",+ "LICENSE",+ "install.ps1" if host_goos == "windows" else "install.sh",+ "THIRD_PARTY_NOTICES.md",+ pack_a_name,+ },+ "UI archive must contain exactly the five base members plus its verified pack "+ f"(got {sorted(ui_members)!r})",+ )++ wrong_pack, wrong_pack_archive = package_fixture(+ work,+ "ui-wrong-pack",+ "ui",+ integration_marker,+ pack_b_name,+ pack_b,+ pack_a_name,+ "fixture-pack-a",+ )+ require(+ wrong_pack.returncode != 0+ and "staged binary rejected its adjacent runtime assets" in wrong_pack.stdout+ and not wrong_pack_archive.exists(),+ "release packager accepted a structurally valid, self-hashed UI pack for a different binary",+ )++ wrong_manifest, wrong_manifest_archive = package_fixture(+ work,+ "standard-wrong-manifest",+ "standard",+ "manifest-association-that-is-not-in-the-repository-asset",+ )+ require(+ wrong_manifest.returncode != 0+ and "staged binary rejected its adjacent runtime assets" in wrong_manifest.stdout+ and not wrong_manifest_archive.exists(),+ "release packager accepted a valid integration manifest that did not match the binary",+ )++if failures:+ print("FAIL: package runtime-asset contract", file=sys.stderr)+ for failure in failures:+ print(f" - {failure}", file=sys.stderr)+ raise SystemExit(1)++print("PASS: release and package-manager runtime assets stay bound to their executable")+PYdiff --git a/tests/test_pipeline.c b/tests/test_pipeline.cindex 7b7dd173d..61d920430 100644--- a/tests/test_pipeline.c+++ b/tests/test_pipeline.c@@ -9892,8 +9892,9 @@ TEST(pipeline_fastapi_depends_edges) {PASS();}-/* DLL resolve test removed — feature removed due to Windows Defender- * false positive (Wacatac.B!ml). See issue #89. */+/* DLL resolve test removed after the associated builds received a Windows+ * Defender Wacatac.B!ml verdict. The opaque verdict did not attribute the+ * result to this feature; see issue #89 for the historical observation. *//* ═══════════════════════════════════════════════════════════════════* Incremental reindexdiff --git a/tests/test_release_archive_extractor_contract.sh b/tests/test_release_archive_extractor_contract.shnew file mode 100644index 000000000..60ce4ed27--- /dev/null+++ b/tests/test_release_archive_extractor_contract.sh@@ -0,0 +1,505 @@+#!/usr/bin/env bash+# Contract for the release scan boundary: exact archives, exact members,+# independently parsed UI-pack assets, byte-exact deduplication and atomic+# publication of a complete association manifest plus scan set.+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"++python3 - "$ROOT" <<'PY'+from __future__ import annotations++import csv+import hashlib+import io+import pathlib+import stat+import struct+import subprocess+import sys+import tarfile+import tempfile+import warnings+import zipfile+from typing import Dict, List, Optional, Tuple+++root = pathlib.Path(sys.argv[1])+extractor = root / "scripts/ci/extract-release-archives.sh"+unix_targets = (+ "linux-amd64",+ "linux-arm64",+ "darwin-amd64",+ "darwin-arm64",+ "linux-amd64-portable",+ "linux-arm64-portable",+)+windows_targets = ("windows-amd64", "windows-arm64")+archive_names = tuple(+ sorted(+ [+ f"codebase-memory-mcp{suffix}-{target}.tar.gz"+ for suffix in ("", "-ui")+ for target in unix_targets+ ]+ + [+ f"codebase-memory-mcp{suffix}-{target}.zip"+ for suffix in ("", "-ui")+ for target in windows_targets+ ]+ )+)+expected_base_counts = {+ "archives": 16,+ "binaries": 16,+ "packs": 8,+ "runtime_files": 64,+}+count_args = [+ f"--expect-{key.replace('_', '-')}={value}"+ for key, value in expected_base_counts.items()+]+asset_payloads = {+ "/assets/app.css": b"body{color:#123}\n",+ "/assets/app.js": b"globalThis.__CBM_UI__ = true;\n",+ "/index.html": b"<!doctype html><script src='/assets/app.js'></script>\n",+}+mime_ids = {".html": 1, ".js": 2, ".css": 3}+++def fail(message: str) -> None:+ raise AssertionError(message)+++def is_ui(name: str) -> bool:+ return name.startswith("codebase-memory-mcp-ui-")+++def make_pack(payloads: Dict[str, bytes]) -> bytes:+ entries = sorted(payloads.items())+ paths = [path.encode("ascii") for path, _ in entries]+ index_size = len(entries) * 24+ paths_size = sum(len(path) for path in paths)+ payload_size = sum(len(data) for _, data in entries)+ paths_offset = 80 + index_size+ payload_offset = paths_offset + paths_size+ total = payload_offset + payload_size+ pack = bytearray(total)+ struct.pack_into(+ "<8sHHIIIQQQQQQQ",+ pack,+ 0,+ b"CBMUIPK\0",+ 1,+ 80,+ 0,+ len(entries),+ 24,+ 80,+ index_size,+ paths_offset,+ paths_size,+ payload_offset,+ payload_size,+ total,+ )+ path_cursor = 0+ payload_cursor = 0+ for index, ((path, data), raw_path) in enumerate(zip(entries, paths)):+ extension = pathlib.PurePosixPath(path).suffix+ struct.pack_into(+ "<IHBBQQ",+ pack,+ 80 + index * 24,+ path_cursor,+ len(raw_path),+ mime_ids[extension],+ 1 if path == "/index.html" else 2,+ payload_cursor,+ len(data),+ )+ pack[paths_offset + path_cursor : paths_offset + path_cursor + len(raw_path)] = raw_path+ pack[payload_offset + payload_cursor : payload_offset + payload_cursor + len(data)] = data+ path_cursor += len(raw_path)+ payload_cursor += len(data)+ return bytes(pack)+++valid_pack = make_pack(asset_payloads)+++def mutate_pack(kind: str) -> bytes:+ data = bytearray(valid_pack)+ if kind == "bad_pack_magic":+ data[0] = ord("X")+ elif kind == "bad_pack_bounds":+ struct.pack_into("<Q", data, 72, len(data) + 1)+ elif kind == "bad_pack_path":+ _, _, _, _, _, _, _, index_size, paths_offset, _, _, _, _ = struct.unpack_from(+ "<8sHHIIIQQQQQQQ", data, 0+ )+ del index_size+ first_length = struct.unpack_from("<H", data, 84)[0]+ replacement = b"/evilxx/app.css"+ if len(replacement) != first_length:+ fail("bad-path fixture length drifted")+ data[paths_offset : paths_offset + first_length] = replacement+ elif kind == "bad_pack_mime":+ data[86] = 2 # first entry is app.css, whose closed MIME id is 3+ else:+ fail(f"unknown pack mutation: {kind}")+ return bytes(data)+++def regular(name: str, data: bytes) -> Dict[str, object]:+ return {"name": name, "kind": "regular", "data": data}+++def archive_entries(name: str, mutation: Optional[str] = None) -> List[Dict[str, object]]:+ marker = name.encode("ascii")+ windows = name.endswith(".zip")+ binary = "codebase-memory-mcp.exe" if windows else "codebase-memory-mcp"+ installer = "install.ps1" if windows else "install.sh"+ entries = [+ regular(binary, b"binary bytes from " + marker + b"\n"),+ regular("cbm-integrations.json", b'{"schema":1,"integrations":[]}\n'),+ regular("LICENSE", b"shared release license\n"),+ regular(+ installer,+ b"Write-Output 'shared installer'\n"+ if windows+ else b"#!/bin/sh\n# shared installer\n",+ ),+ regular("THIRD_PARTY_NOTICES.md", b"shared third-party notices\n"),+ ]+ if is_ui(name):+ pack = mutate_pack(mutation) if mutation and mutation.startswith("bad_pack_") else valid_pack+ entries.append(regular(f"cbm-ui-{hashlib.sha256(pack).hexdigest()}.pack", pack))+ return entries+++def write_archive(path: pathlib.Path, entries: List[Dict[str, object]]) -> None:+ if path.name.endswith(".tar.gz"):+ with tarfile.open(path, "w:gz") as archive:+ for entry in entries:+ name = str(entry["name"])+ kind = str(entry["kind"])+ info = tarfile.TarInfo(name)+ info.mtime = 1+ if kind == "regular":+ data = bytes(entry["data"])+ info.mode = 0o755 if name == "codebase-memory-mcp" else 0o644+ info.size = len(data)+ archive.addfile(info, io.BytesIO(data))+ elif kind == "directory":+ info.type = tarfile.DIRTYPE+ info.mode = 0o755+ archive.addfile(info)+ elif kind == "symlink":+ info.type = tarfile.SYMTYPE+ info.linkname = str(entry["target"])+ archive.addfile(info)+ else:+ fail(f"unknown fixture entry kind: {kind}")+ return+ with warnings.catch_warnings():+ warnings.simplefilter("ignore", UserWarning)+ with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive:+ for entry in entries:+ name = str(entry["name"])+ kind = str(entry["kind"])+ info = zipfile.ZipInfo(name)+ info.create_system = 3+ if kind == "regular":+ mode = 0o755 if name == "codebase-memory-mcp.exe" else 0o644+ info.external_attr = (stat.S_IFREG | mode) << 16+ archive.writestr(info, bytes(entry["data"]))+ elif kind == "directory":+ if not name.endswith("/"):+ info.filename += "/"+ info.external_attr = ((stat.S_IFDIR | 0o755) << 16) | 0x10+ archive.writestr(info, b"")+ elif kind == "symlink":+ info.external_attr = (stat.S_IFLNK | 0o777) << 16+ archive.writestr(info, str(entry["target"]).encode("ascii"))+ else:+ fail(f"unknown fixture entry kind: {kind}")+++Association = Tuple[str, str, str, str]+++def build_matrix(+ archive_dir: pathlib.Path,+ mutation: Optional[str] = None,+) -> Dict[Association, bytes]:+ archive_dir.mkdir(parents=True)+ expected: Dict[Association, bytes] = {}+ targets = {+ "bad_hash": "codebase-memory-mcp-ui-linux-amd64.tar.gz",+ "bad_pack_magic": "codebase-memory-mcp-ui-linux-amd64.tar.gz",+ "bad_pack_bounds": "codebase-memory-mcp-ui-linux-arm64.tar.gz",+ "bad_pack_path": "codebase-memory-mcp-ui-darwin-amd64.tar.gz",+ "bad_pack_mime": "codebase-memory-mcp-ui-darwin-arm64.tar.gz",+ "directory": "codebase-memory-mcp-linux-amd64.tar.gz",+ "extra_pack": "codebase-memory-mcp-ui-linux-arm64-portable.tar.gz",+ "missing_pack": "codebase-memory-mcp-ui-windows-arm64.zip",+ "nested_member": "codebase-memory-mcp-darwin-amd64.tar.gz",+ "tar_symlink": "codebase-memory-mcp-linux-arm64.tar.gz",+ "tar_duplicate": "codebase-memory-mcp-ui-linux-amd64-portable.tar.gz",+ "zip_symlink": "codebase-memory-mcp-windows-amd64.zip",+ "zip_directory": "codebase-memory-mcp-windows-arm64.zip",+ "zip_duplicate": "codebase-memory-mcp-ui-windows-amd64.zip",+ }+ target = targets.get(mutation)+ for name in archive_names:+ if mutation == "missing_archive" and name == "codebase-memory-mcp-linux-amd64.tar.gz":+ continue+ pack_mutation = mutation if name == target and mutation and mutation.startswith("bad_pack_") else None+ entries = archive_entries(name, pack_mutation)+ if name == target:+ if mutation == "bad_hash":+ entries = [entry for entry in entries if not str(entry["name"]).endswith(".pack")]+ entries.append(regular(f"cbm-ui-{'0' * 64}.pack", valid_pack))+ elif mutation in ("directory", "zip_directory"):+ entries.append({"name": "nested/", "kind": "directory"})+ elif mutation in ("tar_duplicate", "zip_duplicate"):+ entries.append(regular("LICENSE", b"second license body\n"))+ elif mutation == "extra_pack":+ second = make_pack({+ "/assets/other.js": b"console.log('other')\n",+ "/index.html": b"<!doctype html>other\n",+ })+ entries.append(regular(f"cbm-ui-{hashlib.sha256(second).hexdigest()}.pack", second))+ elif mutation == "missing_pack":+ entries = [entry for entry in entries if not str(entry["name"]).endswith(".pack")]+ elif mutation == "nested_member":+ entries.append(regular("nested/payload", b"unexpected nested member\n"))+ elif mutation in ("tar_symlink", "zip_symlink"):+ installer = "install.ps1" if name.endswith(".zip") else "install.sh"+ entries = [entry for entry in entries if entry["name"] != installer]+ entries.append({"name": installer, "kind": "symlink", "target": "LICENSE"})+ path = archive_dir / name+ write_archive(path, entries)+ if mutation is None:+ expected[("archive", name, "", "")] = path.read_bytes()+ for entry in entries:+ if entry["kind"] != "regular":+ continue+ member = str(entry["name"])+ data = bytes(entry["data"])+ expected[("member", name, member, "")] = data+ if member.endswith(".pack"):+ for asset_path, payload in asset_payloads.items():+ expected[("pack_asset", name, member, asset_path)] = payload+ if mutation == "unexpected_archive":+ unexpected = "codebase-memory-mcp-freebsd-amd64.tar.gz"+ write_archive(archive_dir / unexpected, archive_entries("codebase-memory-mcp-linux-amd64.tar.gz"))+ if mutation == "oversized_archive":+ with (archive_dir / "codebase-memory-mcp-linux-amd64.tar.gz").open("r+b") as handle:+ handle.truncate(512 * 1024 * 1024 + 1)+ return expected+++def invoke(+ archive_dir: pathlib.Path,+ output_dir: pathlib.Path,+ args: Optional[List[str]] = None,+) -> subprocess.CompletedProcess:+ return subprocess.run(+ ["bash", str(extractor), str(archive_dir), str(output_dir), *(args or count_args)],+ cwd=root,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ check=False,+ )+++def parse_manifest(path: pathlib.Path, marker: str) -> Tuple[Dict[str, int], List[Dict[str, str]]]:+ lines = path.read_text(encoding="utf-8").splitlines()+ if not lines or lines[0] != f"# {marker}":+ fail(f"{path.name} is missing marker {marker}")+ metadata: Dict[str, int] = {}+ cursor = 1+ while cursor < len(lines) and lines[cursor].startswith("# "):+ key, value = lines[cursor][2:].split("=", 1)+ metadata[key] = int(value)+ cursor += 1+ return metadata, list(csv.DictReader(lines[cursor:], delimiter="\t"))+++def assert_clean_failure(case_root: pathlib.Path, mutation: str, message: str) -> None:+ archive_dir = case_root / "archives"+ output_dir = case_root / "scan"+ build_matrix(archive_dir, mutation)+ result = invoke(archive_dir, output_dir)+ if result.returncode == 0 or message not in result.stdout:+ fail(+ f"{mutation}: extractor must fail with {message!r}; "+ f"rc={result.returncode}, output={result.stdout.strip()}"+ )+ if output_dir.exists():+ fail(f"{mutation}: rejected archives left a partial atomic scan bundle")+++if len(archive_names) != 16:+ fail("fixture matrix itself no longer describes 16 canonical archives")++with tempfile.TemporaryDirectory(prefix="cbm-release-scan-contract-") as temporary:+ work = pathlib.Path(temporary)+ valid = work / "valid"+ expected = build_matrix(valid / "archives")+ output = valid / "scan"+ result = invoke(valid / "archives", output)+ if result.returncode != 0:+ fail(f"canonical release matrix was rejected: {result.stdout.strip()}")+ if {path.name for path in output.iterdir()} != {"objects", "associations.tsv", "scan-set.tsv"}:+ fail("scan bundle must publish exactly objects/ plus its two manifests")++ association_metadata, rows = parse_manifest(+ output / "associations.tsv", "cbm-release-scan-associations-v2"+ )+ expected_pack_assets = 8 * len(asset_payloads)+ expected_associations = 16 + 88 + expected_pack_assets+ expected_metadata = {+ **expected_base_counts,+ "pack_assets": expected_pack_assets,+ "associations": expected_associations,+ "scan_objects": len(set(expected.values())),+ }+ if association_metadata != expected_metadata:+ fail(f"association metadata mismatch: {association_metadata!r}")+ if len(rows) != expected_associations:+ fail("association manifest does not contain every archive/member/asset association")+ actual_associations = {+ (row["association_type"], row["archive"], row["member"], row["asset_path"]): row+ for row in rows+ }+ if set(actual_associations) != set(expected):+ fail("association manifest keys differ from exact shipped associations")+ for association, data in expected.items():+ row = actual_associations[association]+ object_path = output / row["scan_path"]+ if object_path.read_bytes() != data:+ fail(f"scan object changed bytes for association {association!r}")+ if row["object_sha256"] != hashlib.sha256(data).hexdigest() or int(row["size"]) != len(data):+ fail(f"association digest/size is wrong for {association!r}")++ object_paths = sorted((output / "objects").iterdir())+ if len(object_paths) != len(set(expected.values())):+ fail("byte-identical archive members/assets were not deduplicated")+ object_bytes = [path.read_bytes() for path in object_paths]+ if len(object_bytes) != len(set(object_bytes)):+ fail("scan set contains duplicate byte sequences")+ license_rows = [row for row in rows if row["member"] == "LICENSE"]+ if len(license_rows) != 16 or len({row["scan_path"] for row in license_rows}) != 1:+ fail("shared LICENSE bytes must map 16 associations to one scan object")+ pack_rows = [row for row in rows if row["kind"] == "pack"]+ if len(pack_rows) != 8 or len({row["scan_path"] for row in pack_rows}) != 1:+ fail("shared UI pack bytes must map eight associations to one scan object")+ script_rows = [row for row in rows if row["asset_path"] == "/assets/app.js"]+ if len(script_rows) != 8 or len({row["scan_path"] for row in script_rows}) != 1:+ fail("each pack's JavaScript association must reach one exact deduplicated script object")++ scan_metadata, scan_rows = parse_manifest(output / "scan-set.tsv", "cbm-release-scan-set-v1")+ if scan_metadata != {+ "scan_objects": expected_metadata["scan_objects"],+ "associations": expected_associations,+ }:+ fail(f"scan-set metadata mismatch: {scan_metadata!r}")+ if len(scan_rows) != len(object_paths):+ fail("scan-set row count differs from staged distinct objects")+ scan_paths = {row["scan_path"] for row in scan_rows}+ if scan_paths != {f"objects/{path.name}" for path in object_paths}:+ fail("scan-set paths differ from staged object paths")+ if sum(int(row["association_count"]) for row in scan_rows) != expected_associations:+ fail("scan-set association counts do not cover the association manifest")+ for row in scan_rows:+ path = output / row["scan_path"]+ data = path.read_bytes()+ if row["sha256"] != hashlib.sha256(data).hexdigest() or int(row["size"]) != len(data):+ fail(f"scan-set digest/size does not bind {row['scan_path']}")++ failure_cases = {+ "bad_hash": "UI pack digest does not match its filename",+ "bad_pack_magic": "CBMUIPK header/offset contract failed",+ "bad_pack_bounds": "CBMUIPK header/offset contract failed",+ "bad_pack_path": "CBMUIPK asset path is invalid",+ "bad_pack_mime": "CBMUIPK MIME/path contract failed",+ "directory": "non-regular archive member",+ "extra_pack": "exactly one UI pack",+ "missing_archive": "expected exact canonical 16",+ "missing_pack": "exactly one UI pack",+ "nested_member": "unexpected archive member",+ "oversized_archive": "archive exceeds 536870912 byte ceiling",+ "tar_symlink": "non-regular archive member",+ "tar_duplicate": "duplicate archive member",+ "unexpected_archive": "expected exact canonical 16",+ "zip_directory": "non-regular archive member",+ "zip_duplicate": "duplicate archive member",+ "zip_symlink": "non-regular archive member",+ }+ for mutation, message in failure_cases.items():+ case_root = work / mutation+ case_root.mkdir()+ assert_clean_failure(case_root, mutation, message)++ wrong_count = work / "wrong-count"+ wrong_count.mkdir()+ build_matrix(wrong_count / "archives")+ wrong_args = [arg for arg in count_args if not arg.startswith("--expect-packs=")]+ wrong_args.append("--expect-packs=9")+ wrong_output = wrong_count / "scan"+ wrong = invoke(wrong_count / "archives", wrong_output, wrong_args)+ if wrong.returncode == 0 or "packs expected 9, got 8" not in wrong.stdout or wrong_output.exists():+ fail(f"explicit expected-count mismatch did not fail atomically: {wrong.stdout.strip()}")++source = extractor.read_text(encoding="utf-8")+if "files_equal(candidate, existing.path)" not in source:+ fail("deduplication no longer exact-compares bytes after SHA-256+size grouping")+if source.count("archive_object.path,") < 2:+ fail("members are not parsed from the same retained bytes staged as the archive object")+for ceiling in ("MAX_ARCHIVE_BYTES", "MAX_MEMBER_BYTES", "MAX_TOTAL_MEMBER_BYTES"):+ if ceiling not in source:+ fail(f"extractor lost required size ceiling {ceiling}")++release = (root / ".github/workflows/release.yml").read_text(encoding="utf-8")+dry_run = (root / ".github/workflows/dry-run.yml").read_text(encoding="utf-8")+for workflow_name, workflow in (("release", release), ("dry-run", dry_run)):+ for argument in count_args:+ if argument not in workflow:+ fail(f"{workflow_name} workflow does not assert {argument}")+ for required in (+ "files: binaries/objects/*",+ "request_rate: 4",+ "VT_EXPECTED_SCAN_SET: binaries/scan-set.tsv",+ "VT_ASSOCIATIONS: binaries/associations.tsv",+ "VT_RESULTS_PATH: binaries/vt-results.tsv",+ "MIN_ENGINES: 50",+ "actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a",+ "virustotal-evidence-",+ ):+ if required not in workflow:+ fail(f"{workflow_name} workflow is missing exact scan/gate contract: {required}")+ lowered = workflow.lower()+ for forbidden in ("false-positive", "false positive", "submission", "reputation"):+ if forbidden in lowered:+ fail(f"{workflow_name} workflow prescribes forbidden scan-cleaning policy: {forbidden}")+ if "naturally clean" not in lowered:+ fail(f"{workflow_name} workflow must state the naturally-clean baseline")++notes = (root / "scripts/ci/append-vt-notes.sh").read_text(encoding="utf-8")+for required in (+ "cbm-security-verification:start",+ "cbm-security-verification:end",+ "binaries/associations.tsv",+ "binaries/vt-results.tsv",+):+ if required not in notes:+ fail(f"release-note updater is missing {required}")+if "70+" in notes or "...`" in notes:+ fail("release notes must use measured engine counts and full SHA-256 values")++print("release archive extractor contract: OK")+PYdiff --git a/tests/test_security.c b/tests/test_security.cindex 8f2731984..fc81f644b 100644--- a/tests/test_security.c+++ b/tests/test_security.c@@ -75,7 +75,8 @@ TEST(vendored_integrity_manifest_is_relocatable_and_fail_closed) {if (sscanf(line, "%64s %3899s", hash, path) != 2)continue;ASSERT_EQ(strlen(hash), 64U);- ASSERT(strncmp(path, "vendored/", strlen("vendored/")) == 0);+ ASSERT(strncmp(path, "vendored/", strlen("vendored/")) == 0 ||+ strncmp(path, "internal/cbm/vendored/", strlen("internal/cbm/vendored/")) == 0);entries++;}fclose(checksums);diff --git a/tests/test_smoke_fixture_contract.sh b/tests/test_smoke_fixture_contract.shindex 111b5c7cd..177d38621 100755--- a/tests/test_smoke_fixture_contract.sh+++ b/tests/test_smoke_fixture_contract.sh@@ -8,10 +8,13 @@ ROOT="$(cd "$(dirname "$0")/.." && pwd)"python3 - "$ROOT" <<'PY'from __future__ import annotations+import hashlib+import osimport pathlibimport reimport subprocessimport sys+import tarfileimport tempfileimport timeimport urllib.request@@ -44,9 +47,29 @@ local_ci = read("test-infrastructure/run.sh")windows_vm = read("test-infrastructure/vm/win.sh")windows_vm_runner = read("test-infrastructure/vm/vm-run-tests.sh")pr_workflow = read(".github/workflows/pr.yml")+release_workflow = read(".github/workflows/release.yml")+release_extractor = read("scripts/ci/extract-release-archives.sh")test_driver = read("scripts/test.sh")cli_source = read("src/cli/cli.c")helper_source = read(helper_relative)+unix_installer = read("install.sh")+windows_installer = read("install.ps1")++# Keep the security-boundary archive checks runnable as a focused, network-free+# contract while still making them part of the canonical smoke-fixture gate.+release_archive_contract = subprocess.run(+ ["bash", str(root / "tests/test_release_archive_extractor_contract.sh")],+ cwd=root,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ check=False,+)+require(+ release_archive_contract.returncode == 0,+ "release archive extractor contract failed: "+ + release_archive_contract.stdout.strip(),+)# The server owns the ephemeral bind. A parent-side socket probe followed by# python -m http.server would reintroduce the close/rebind race this guards.@@ -134,18 +157,23 @@ for relative, source in (f"{relative} must pin isolated {variable}",)-# Unix fixtures mirror the release archive surface and Linux update aliases.+# Unix fixtures mirror the exact release variant surface.for name in ("LICENSE", "install.sh", "THIRD_PARTY_NOTICES.md"):require(name in smoke_local, f"smoke-local.sh archive must include {name}")require("codebase-memory-mcp${SUFFIX}-${OS}-${ARCH}.tar.gz" in smoke_local- and "codebase-memory-mcp-${OS}-${ARCH}.tar.gz" in smoke_local,- "smoke-local.sh must create the selected variant and standard alias",+ and "UI_PACK_NAME" in smoke_local+ and "^cbm-ui-[0-9a-f]{64}\\.pack$" in smoke_local,+ "smoke-local.sh must create the selected exact variant with a hash-shaped UI pack",)require("codebase-memory-mcp${SUFFIX}-${OS}-${ARCH}-portable.tar.gz" in smoke_local- and "codebase-memory-mcp-${OS}-${ARCH}-portable.tar.gz" in smoke_local,- "smoke-local.sh must create Linux portable selected-variant and standard aliases",+ and 'ARCHIVE_MEMBERS+=("$UI_PACK_NAME")' in smoke_local,+ "smoke-local.sh must create the Linux portable selected variant with the same member set",+)+require(+ '"$FIXTURE_DIR/codebase-memory-mcp-${OS}-${ARCH}.tar.gz"' not in smoke_local,+ "smoke-local.sh must not disguise a six-member UI archive under a standard name",)require('CBM_CACHE_DIR="$WORK_DIR/cache"' in smoke_local@@ -163,9 +191,9 @@ require("fixture checksums must name exact artifact basenames, never ./-prefixed paths",)-# Native Windows packages and serves the exact four-file release bundle (ONE-# binary, like every other platform), then runs the full smoke from a protected-# profile-rooted directory/cache.+# Native Windows packages and serves the exact five-file standard bundle or+# six-file UI bundle (one native binary), then runs the full smoke from a+# protected profile-rooted directory/cache.for name in ("codebase-memory-mcp.exe","LICENSE",@@ -178,6 +206,16 @@ require("vm-smoke.sh must not stage a Windows launcher/payload pair",)require("checksums.txt" in vm_smoke, "vm-smoke.sh must generate checksums.txt")+require(+ "UI_PACK_NAME" in vm_smoke+ and "^cbm-ui-[0-9a-f]{64}\\.pack$" in vm_smoke+ and 'ARCHIVE_MEMBERS+=("$UI_PACK_NAME")' in vm_smoke,+ "vm-smoke.sh must stage exactly one content-addressed pack only for UI",+)+require(+ '"codebase-memory-mcp-windows-${SMOKE_ARCH}.zip"' not in vm_smoke,+ "vm-smoke.sh must not disguise a six-member UI zip under a standard name",+)require("SMOKE_DOWNLOAD_URL=" in vm_smokeand "SMOKE_UPDATE_FIXTURE_DIR=" in vm_smoke@@ -262,7 +300,7 @@ for service in ("smoke-windows:",):require("wine64 ./build/win-cross/codebase-memory-mcp.exe --version" in composeand "wine64 cmd /c build/win-cross/codebase-memory-mcp.exe --version" in compose,- "docker-compose Windows cross-smoke must execute the single binary through Wine and through a "+ "docker-compose Windows cross-smoke must execute the runtime set's one executable through Wine and through a ""Wine Windows parent",)require(@@ -305,6 +343,92 @@ require("PR Windows smoke must call vm-smoke.sh with SMOKE_ARCH=amd64",)smoke_test = read("scripts/smoke-test.sh")+require(+ "SMOKE_UI_PACK_CANDIDATES" in smoke_test+ and 'cp "$SMOKE_UI_PACK" "$(dirname "$destination")/$(basename "$SMOKE_UI_PACK")"'+ in smoke_test,+ "smoke-test.sh must stage the UI sidecar with every hand-copied binary",+)+require(+ 'UNINSTALL_BINARY="$SELF_PATH"' in smoke_test+ and '"$CLEAN_UNINSTALLER" uninstall -y -n' in smoke_test+ and '"$DBL_UNINSTALLER" uninstall -y -n' in smoke_test+ and '"$DBL_RETRY_UNINSTALLER" uninstall -y -n' in smoke_test,+ "smoke uninstall cases must run disposable fixture executables, never delete the "+ "build input needed by later phases",+)+require(+ 'exec 9< <(sleep 300)' in smoke_test+ and 'UI_STDIN_PID=$!' in smoke_test+ and smoke_test.count("stop_ui_probe") >= 4+ and 'sleep 300 | "$BINARY"' not in smoke_test,+ "the UI readiness probe must own and reap its stdin keeper instead of waiting on a "+ "background pipeline",+)+require(+ '"$REPO_ROOT/install.sh" "$DL_VARIANT_ARG"' in smoke_test+ and '"$WIN_SCRIPT" "$DL_VARIANT_ARG"' in smoke_test+ and "install.ps1 did not publish exactly one UI asset pack" in smoke_test,+ "Phase 13 must call each direct installer with the downloaded variant and verify its pack",+)+require(+ all(+ needle in unix_installer+ for needle in (+ "ARCHIVE_MEMBER_COUNT",+ "EXPECTED_MEMBER_COUNT=5",+ "EXPECTED_MEMBER_COUNT=6",+ "^cbm-ui-[0-9a-f]{64}\\.pack$",+ "release archive contains unexpected member",+ )+ ),+ "install.sh must validate the exact five-member standard or six-member UI archive",+)+unix_binary_publish = unix_installer.find('"$DLBIN" install "${INSTALL_ARGS[@]}"')+require(+ unix_binary_publish >= 0+ and "publish_required_sidecar" not in unix_installer+ and 'for stale_pack in "$INSTALL_DIR"/cbm-ui-*.pack' not in unix_installer,+ "install.sh must delegate sidecar publication and stale-pack GC to the candidate's "+ "guarded native install",+)+require(+ "GetRandomFileName" in windows_installer+ and "[System.IO.FileMode]::CreateNew" in windows_installer+ and windows_installer.count("New-CbmExclusiveSiblingTemp") == 2+ and '$Destination.new-$PID' not in windows_installer+ and '$InstallerDest.new' not in windows_installer,+ "install.ps1 must reserve an unpredictable sibling temp exclusively for the updater only",+)++cli_source = read("src/cli/cli.c")+install_start = cli_source.find("static int cli_install_activate(void *opaque)")+install_end = cli_source.find("int cbm_cmd_install(", install_start)+install_body = cli_source[install_start:install_end] if 0 <= install_start < install_end else ""+runtime_stage = install_body.find("cbm_integration_assets_stage_install")+binary_commit = install_body.find("cli_activation_transaction_commit_validated")+runtime_gc = install_body.find("cli_gc_stale_ui_asset_packs")+runtime_finalize = install_body.find("cli_install_runtime_finalize")+require(+ 0 <= runtime_stage < binary_commit < runtime_gc < runtime_finalize,+ "native install must stage sidecars, activate the binary, GC verified stale packs, and "+ "finalize while the activation callback still owns the guard",+)+require(+ "scripts/ci/extract-release-archives.sh assets binaries" in release_workflow,+ "release verification must use the canonical archive extractor",+)+require(+ "cbm-release-scan-associations-v2" in release_extractor+ and "cbm-release-scan-set-v1" in release_extractor+ and "files_equal(candidate, existing.path)" in release_extractor+ and "parse_pack_assets" in release_extractor+ and "PACK_NAME.fullmatch" in release_extractor+ and "non-regular archive member" in release_extractor+ and "duplicate archive member" in release_extractor,+ "release extraction must validate every exact archive/member/UI-asset association "+ "and retain one exact-compared scan object per distinct byte sequence",+)require("MSYS2_ARG_CONV_EXCL='*'" in smoke_testand 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File' in smoke_test@@ -523,6 +647,218 @@ if helper.is_file():dns_process.kill()dns_process.wait(timeout=3)+# POSIX installer lifecycle injection. Preserve the wrapper's PID across exec,+# precreate the two formerly predictable temp paths as foreign symlinks, then+# run the real checksum-authenticated installer. The script no longer publishes+# runtime sidecars at all, and its updater publisher never touches the foreign+# predictable sibling.+if os.name != "nt" and helper.is_file():+ with tempfile.TemporaryDirectory(prefix="cbm-installer-temp-contract-") as install_temp:+ install_root = pathlib.Path(install_temp)+ fixture = install_root / "fixture"+ stage = install_root / "stage"+ fake_bin = install_root / "fake-bin"+ install_dir = install_root / "installed"+ fake_home = install_root / "home"+ fixture.mkdir()+ stage.mkdir()+ fake_bin.mkdir()+ install_dir.mkdir()+ fake_home.mkdir()++ candidate = stage / "codebase-memory-mcp"+ candidate.write_text(+ "#!/usr/bin/env bash\n"+ "set -euo pipefail\n"+ "case \"${1:-}\" in\n"+ " --version) echo 'codebase-memory-mcp fixture';;\n"+ " install)\n"+ " install_dir=''\n"+ " for arg in \"$@\"; do\n"+ " case \"$arg\" in --dir=*) install_dir=${arg#--dir=};; esac\n"+ " done\n"+ " test -n \"$install_dir\"\n"+ " cp \"$0\" \"$install_dir/codebase-memory-mcp\"\n"+ " chmod 755 \"$install_dir/codebase-memory-mcp\";;\n"+ " *) exit 2;;\n"+ "esac\n",+ encoding="utf-8",+ )+ candidate.chmod(0o755)+ (stage / "cbm-integrations.json").write_bytes(b"{}\n")+ (stage / "LICENSE").write_bytes(b"fixture license\n")+ (stage / "THIRD_PARTY_NOTICES.md").write_bytes(b"fixture notices\n")++ archive_name = "codebase-memory-mcp-linux-amd64-portable.tar.gz"+ archive_path = fixture / archive_name+ with tarfile.open(archive_path, "w:gz") as archive:+ for name in (+ "codebase-memory-mcp",+ "cbm-integrations.json",+ "LICENSE",+ "THIRD_PARTY_NOTICES.md",+ ):+ archive.add(stage / name, arcname=name)+ archive.add(root / "install.sh", arcname="install.sh")+ archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()+ (fixture / "checksums.txt").write_text(+ f"{archive_digest} {archive_name}\n", encoding="ascii"+ )++ fake_uname = fake_bin / "uname"+ fake_uname.write_text(+ "#!/bin/sh\n"+ "case \"${1:-}\" in\n"+ " -s) echo Linux;;\n"+ " -m) echo x86_64;;\n"+ " *) echo Linux;;\n"+ "esac\n",+ encoding="utf-8",+ )+ fake_uname.chmod(0o755)++ foreign_sidecar = install_root / "foreign-sidecar"+ foreign_updater = install_root / "foreign-updater"+ foreign_sidecar.write_bytes(b"foreign sidecar sentinel\n")+ foreign_updater.write_bytes(b"foreign updater sentinel\n")+ wrapper_pid_file = install_root / "wrapper-pid"+ wrapper = install_root / "run-installer.sh"+ wrapper.write_text(+ "#!/usr/bin/env bash\n"+ "set -euo pipefail\n"+ "install_dir=$1\n"+ "foreign_sidecar=$2\n"+ "foreign_updater=$3\n"+ "pid_file=$4\n"+ "installer=$5\n"+ "ln -s \"$foreign_sidecar\" \"$install_dir/.cbm-integrations.json.$$\"\n"+ "ln -s \"$foreign_updater\" \"$install_dir/.install.sh.$$\"\n"+ "printf '%s\\n' \"$$\" > \"$pid_file\"\n"+ "exec bash \"$installer\" --standard \"--dir=$install_dir\" --skip-config\n",+ encoding="utf-8",+ )+ wrapper.chmod(0o755)++ port_file = install_root / "port"+ server_log = install_root / "server.log"+ with server_log.open("wb") as log_handle:+ fixture_server = subprocess.Popen(+ [+ sys.executable,+ str(helper),+ "--directory",+ str(fixture),+ "--port-file",+ str(port_file),+ ],+ stdout=log_handle,+ stderr=subprocess.STDOUT,+ )+ try:+ port = 0+ deadline = time.monotonic() + 30+ while time.monotonic() < deadline:+ if port_file.is_file():+ try:+ port_text = port_file.read_text(encoding="ascii").strip()+ except OSError:+ port_text = ""+ if port_text:+ port = int(port_text)+ break+ if fixture_server.poll() is not None:+ break+ time.sleep(0.02)+ require(port > 0, "installer temp-path fixture server did not publish a port")+ if port > 0:+ environment = os.environ.copy()+ environment["HOME"] = str(fake_home)+ environment["PATH"] = (+ str(fake_bin) + os.pathsep + environment.get("PATH", "")+ )+ environment["CBM_DOWNLOAD_URL"] = f"http://127.0.0.1:{port}"+ installed = subprocess.run(+ [+ str(wrapper),+ str(install_dir),+ str(foreign_sidecar),+ str(foreign_updater),+ str(wrapper_pid_file),+ str(root / "install.sh"),+ ],+ env=environment,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ timeout=60,+ check=False,+ )+ require(+ installed.returncode == 0,+ f"installer temp-path fixture failed to install: {installed.stdout.strip()}",+ )+ if wrapper_pid_file.is_file():+ wrapper_pid = wrapper_pid_file.read_text(encoding="ascii").strip()+ predictable_sidecar = (+ install_dir / f".cbm-integrations.json.{wrapper_pid}"+ )+ predictable_updater = install_dir / f".install.sh.{wrapper_pid}"+ require(+ predictable_sidecar.is_symlink()+ and foreign_sidecar.read_bytes()+ == b"foreign sidecar sentinel\n",+ "install.sh deleted or followed a foreign predictable sidecar temp",+ )+ require(+ predictable_updater.is_symlink()+ and foreign_updater.read_bytes()+ == b"foreign updater sentinel\n",+ "install.sh deleted or followed a foreign predictable updater temp",+ )+ else:+ failures.append("installer temp-path wrapper did not publish its PID")+ finally:+ fixture_server.terminate()+ try:+ fixture_server.wait(timeout=3)+ except subprocess.TimeoutExpired:+ fixture_server.kill()+ fixture_server.wait(timeout=3)++# The complete canonical-matrix extraction, pack parsing, association retention,+# byte-exact deduplication and fail-closed malformed-pack cases run above via+# test_release_archive_extractor_contract.sh. Keep the packaging-side digest+# check here because it is a separate boundary before an archive exists.+with tempfile.TemporaryDirectory(prefix="cbm-release-extract-") as extract_temp:+ extract_root = pathlib.Path(extract_temp)+ bad_pack_name = f"cbm-ui-{'0' * 64}.pack"+ bad_pack_bytes = b"content does not match the zero digest\n"+ # Packaging checks the content address before it touches the product binary.+ # No binary is staged deliberately: the digest error must win over the+ # later missing-binary guard or this test would accept an incidental red.+ package_build = extract_root / "package-build"+ package_output = extract_root / "package-output"+ package_build.mkdir()+ package_output.mkdir()+ (package_build / bad_pack_name).write_bytes(bad_pack_bytes)+ package_environment = os.environ.copy()+ package_environment["BUILD_DIR"] = str(package_build)+ packaged = subprocess.run(+ ["bash", str(root / "scripts/package-release.sh"), "linux", "amd64",+ "--variant", "ui", "--out-dir", str(package_output)],+ cwd=root,+ env=package_environment,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ check=False,+ )+ require(+ packaged.returncode != 0+ and "UI pack digest does not match its filename" in packaged.stdout,+ "release packager accepted a UI pack whose content did not match its filename",+ )+if failures:print("smoke fixture contract: FAIL", file=sys.stderr)for failure in failures:diff --git a/tests/test_ui.c b/tests/test_ui.cindex a403dbbbe..ba22ee5e6 100644--- a/tests/test_ui.c+++ b/tests/test_ui.c@@ -1,14 +1,15 @@/** test_ui.c — Tests for the graph visualization UI module.*- * Covers: config persistence, embedded asset lookup, layout engine.+ * Covers: config persistence, external asset-pack validation, layout engine.*/#include "../src/foundation/compat.h"#include "../src/foundation/compat_fs.h"#include "test_framework.h"#include "test_helpers.h"+#include "foundation/sha256.h"+#include "ui/asset_pack.h"#include "ui/config.h"-#include "ui/embedded_assets.h"#include "ui/layout3d.h"#include "store/store.h"#ifdef _WIN32@@ -124,9 +125,9 @@ TEST(config_save_atomically_replaces_a_complete_generation) {char old_bytes[512] = {0};#ifdef _WIN32DWORD old_length = 0;- bool old_read = ReadFile(old_handle, old_bytes, (DWORD)sizeof(old_bytes) - 1U, &old_length,- NULL) != 0 &&- old_length > 0;+ bool old_read =+ ReadFile(old_handle, old_bytes, (DWORD)sizeof(old_bytes) - 1U, &old_length, NULL) != 0 &&+ old_length > 0;bool old_closed = CloseHandle(old_handle) != 0;#elsesize_t old_length = fread(old_bytes, 1, sizeof(old_bytes) - 1, old_handle);@@ -259,18 +260,545 @@ TEST(config_missing_fields) {PASS();}-/* ── Embedded asset tests ─────────────────────────────────────── */+/* ── External UI asset-pack tests ────────────────────────────── */-TEST(embedded_lookup_not_found) {- /* With stub, everything should return NULL */- const cbm_embedded_file_t *f = cbm_embedded_lookup("/nonexistent");- ASSERT_NULL(f);+enum {+ TEST_UI_PACK_HEADER_BYTES = 80,+ TEST_UI_PACK_ENTRY_BYTES = 24,+};++static void ui_test_write_u16(unsigned char *bytes, uint16_t value) {+ bytes[0] = (unsigned char)value;+ bytes[1] = (unsigned char)(value >> 8U);+}++static void ui_test_write_u32(unsigned char *bytes, uint32_t value) {+ for (size_t index = 0U; index < sizeof(value); index++) {+ bytes[index] = (unsigned char)(value >> (index * 8U));+ }+}++static void ui_test_write_u64(unsigned char *bytes, uint64_t value) {+ for (size_t index = 0U; index < sizeof(value); index++) {+ bytes[index] = (unsigned char)(value >> (index * 8U));+ }+}++static unsigned char *ui_test_pack(size_t *length_out, bool malformed_index) {+ static const char asset_path[] = "/assets/app.js";+ static const char index_path[] = "/index.html";+ static const unsigned char asset_data[] = "console.log(1);";+ static const unsigned char index_data[] = "<h1>CBM</h1>";+ size_t paths_length = sizeof(asset_path) - 1U + sizeof(index_path) - 1U;+ size_t payload_length = sizeof(asset_data) - 1U + sizeof(index_data) - 1U;+ size_t index_length = TEST_UI_PACK_ENTRY_BYTES * 2U;+ size_t paths_offset = TEST_UI_PACK_HEADER_BYTES + index_length;+ size_t payload_offset = paths_offset + paths_length;+ size_t total = payload_offset + payload_length;+ unsigned char *pack = calloc(total, 1U);+ if (!pack) {+ return NULL;+ }+ pack[0] = 'C';+ pack[1] = 'B';+ pack[2] = 'M';+ pack[3] = 'U';+ pack[4] = 'I';+ pack[5] = 'P';+ pack[6] = 'K';+ ui_test_write_u16(pack + 8U, 1U);+ ui_test_write_u16(pack + 10U, TEST_UI_PACK_HEADER_BYTES);+ ui_test_write_u32(pack + 16U, 2U);+ ui_test_write_u32(pack + 20U, TEST_UI_PACK_ENTRY_BYTES);+ ui_test_write_u64(pack + 24U, TEST_UI_PACK_HEADER_BYTES);+ ui_test_write_u64(pack + 32U, index_length);+ ui_test_write_u64(pack + 40U, paths_offset);+ ui_test_write_u64(pack + 48U, paths_length);+ ui_test_write_u64(pack + 56U, payload_offset);+ ui_test_write_u64(pack + 64U, payload_length);+ ui_test_write_u64(pack + 72U, total);++ unsigned char *asset_entry = pack + TEST_UI_PACK_HEADER_BYTES;+ ui_test_write_u32(asset_entry, malformed_index ? 1U : 0U);+ ui_test_write_u16(asset_entry + 4U, sizeof(asset_path) - 1U);+ asset_entry[6U] = 2U;+ asset_entry[7U] = CBM_UI_ASSET_IMMUTABLE;+ ui_test_write_u64(asset_entry + 8U, 0U);+ ui_test_write_u64(asset_entry + 16U, sizeof(asset_data) - 1U);++ unsigned char *index_entry = asset_entry + TEST_UI_PACK_ENTRY_BYTES;+ ui_test_write_u32(index_entry, sizeof(asset_path) - 1U);+ ui_test_write_u16(index_entry + 4U, sizeof(index_path) - 1U);+ index_entry[6U] = 1U;+ index_entry[7U] = CBM_UI_ASSET_REVALIDATE;+ ui_test_write_u64(index_entry + 8U, sizeof(asset_data) - 1U);+ ui_test_write_u64(index_entry + 16U, sizeof(index_data) - 1U);++ memcpy(pack + paths_offset, asset_path, sizeof(asset_path) - 1U);+ memcpy(pack + paths_offset + sizeof(asset_path) - 1U, index_path, sizeof(index_path) - 1U);+ memcpy(pack + payload_offset, asset_data, sizeof(asset_data) - 1U);+ memcpy(pack + payload_offset + sizeof(asset_data) - 1U, index_data, sizeof(index_data) - 1U);+ *length_out = total;+ return pack;+}++static bool ui_test_publish_pack(const char *directory, unsigned char *pack, size_t length,+ char path_out[1024]) {+ char hash[CBM_SHA256_HEX_LEN + 1U];+ cbm_sha256_hex(pack, length, hash);+ char name[128];+ int name_length = snprintf(name, sizeof(name), "cbm-ui-%s.pack", hash);+ int path_length = snprintf(path_out, 1024U, "%s/%s", directory, name);+ if (name_length <= 0 || (size_t)name_length >= sizeof(name) || path_length <= 0 ||+ path_length >= 1024) {+ return false;+ }+ FILE *file = fopen(path_out, "wb");+ bool written = file && fwrite(pack, 1U, length, file) == length;+ if (file && fclose(file) != 0) {+ written = false;+ }+ if (written) {+ cbm_ui_assets_set_manifest_for_testing(name, hash, length);+ }+ return written;+}++static void ui_test_restore_assets_env(char *old_value) {+ if (old_value) {+ (void)cbm_setenv("CBM_UI_ASSETS_DIR", old_value, 1);+ free(old_value);+ } else {+ (void)cbm_unsetenv("CBM_UI_ASSETS_DIR");+ }+}++TEST(ui_asset_pack_validates_before_publication) {+ char directory[] = "/tmp/cbm_ui_pack_XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(directory));+ size_t length = 0U;+ unsigned char *pack = ui_test_pack(&length, false);+ ASSERT_NOT_NULL(pack);+ char pack_path[1024];+ cbm_ui_assets_reset_for_testing();+ ASSERT_TRUE(ui_test_publish_pack(directory, pack, length, pack_path));+ free(pack);+ char *old_assets = getenv("CBM_UI_ASSETS_DIR") ? strdup(getenv("CBM_UI_ASSETS_DIR")) : NULL;+ ASSERT_EQ(cbm_setenv("CBM_UI_ASSETS_DIR", directory, 1), 0);++ char error[512];+ ASSERT_TRUE(cbm_ui_assets_supported());+ ASSERT_EQ(cbm_ui_assets_state(), CBM_UI_ASSETS_COLD);+ ASSERT_TRUE(cbm_ui_assets_warm(NULL, error, sizeof(error)));+ ASSERT_EQ(cbm_ui_assets_state(), CBM_UI_ASSETS_READY);+ const cbm_ui_asset_t *asset = cbm_ui_asset_lookup("/assets/app.js");+ ASSERT_NOT_NULL(asset);+ ASSERT_EQ(asset->cache, CBM_UI_ASSET_IMMUTABLE);+ ASSERT_STR_EQ(asset->content_type, "application/javascript; charset=utf-8");+ ASSERT_EQ(asset->size, sizeof("console.log(1);") - 1U);+ ASSERT_NULL(cbm_ui_asset_lookup("/api/processes"));++ cbm_ui_assets_reset_for_testing();+ ui_test_restore_assets_env(old_assets);+ (void)cbm_unlink(pack_path);+ (void)cbm_rmdir(directory);+ PASS();+}++TEST(ui_asset_pack_wrong_hash_fails_closed) {+ char directory[] = "/tmp/cbm_ui_hash_XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(directory));+ size_t length = 0U;+ unsigned char *pack = ui_test_pack(&length, false);+ ASSERT_NOT_NULL(pack);+ char pack_path[1024];+ cbm_ui_assets_reset_for_testing();+ ASSERT_TRUE(ui_test_publish_pack(directory, pack, length, pack_path));+ pack[length - 1U] ^= 1U;+ FILE *file = fopen(pack_path, "wb");+ ASSERT_NOT_NULL(file);+ ASSERT_EQ(fwrite(pack, 1U, length, file), length);+ ASSERT_EQ(fclose(file), 0);+ free(pack);+ char *old_assets = getenv("CBM_UI_ASSETS_DIR") ? strdup(getenv("CBM_UI_ASSETS_DIR")) : NULL;+ ASSERT_EQ(cbm_setenv("CBM_UI_ASSETS_DIR", directory, 1), 0);++ char error[512];+ ASSERT_FALSE(cbm_ui_assets_warm(NULL, error, sizeof(error)));+ ASSERT_EQ(cbm_ui_assets_state(), CBM_UI_ASSETS_FAILED);+ ASSERT_NULL(cbm_ui_asset_lookup("/index.html"));++ cbm_ui_assets_reset_for_testing();+ ui_test_restore_assets_env(old_assets);+ (void)cbm_unlink(pack_path);+ (void)cbm_rmdir(directory);+ PASS();+}++TEST(ui_asset_pack_structural_corruption_fails_after_valid_hash) {+ char directory[] = "/tmp/cbm_ui_format_XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(directory));+ size_t length = 0U;+ unsigned char *pack = ui_test_pack(&length, true);+ ASSERT_NOT_NULL(pack);+ char pack_path[1024];+ cbm_ui_assets_reset_for_testing();+ ASSERT_TRUE(ui_test_publish_pack(directory, pack, length, pack_path));+ free(pack);+ char *old_assets = getenv("CBM_UI_ASSETS_DIR") ? strdup(getenv("CBM_UI_ASSETS_DIR")) : NULL;+ ASSERT_EQ(cbm_setenv("CBM_UI_ASSETS_DIR", directory, 1), 0);++ char error[512];+ ASSERT_FALSE(cbm_ui_assets_warm(NULL, error, sizeof(error)));+ ASSERT_EQ(cbm_ui_assets_state(), CBM_UI_ASSETS_FAILED);+ ASSERT_NULL(cbm_ui_asset_lookup("/index.html"));++ cbm_ui_assets_reset_for_testing();+ ui_test_restore_assets_env(old_assets);+ (void)cbm_unlink(pack_path);+ (void)cbm_rmdir(directory);+ PASS();+}++/* A daemon can be asked to stop immediately after creating the warmup thread,+ * before that worker enters cbm_ui_assets_warm(). The cancellation must latch+ * across that scheduling window instead of being cleared by worker startup. */+TEST(ui_asset_pack_prestart_cancellation_is_not_lost) {+ char directory[] = "/tmp/cbm_ui_cancel_XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(directory));+ size_t length = 0U;+ unsigned char *pack = ui_test_pack(&length, false);+ ASSERT_NOT_NULL(pack);+ char pack_path[1024];+ cbm_ui_assets_reset_for_testing();+ ASSERT_TRUE(ui_test_publish_pack(directory, pack, length, pack_path));+ free(pack);+ char *old_assets = getenv("CBM_UI_ASSETS_DIR") ? strdup(getenv("CBM_UI_ASSETS_DIR")) : NULL;+ ASSERT_EQ(cbm_setenv("CBM_UI_ASSETS_DIR", directory, 1), 0);++ cbm_ui_assets_request_cancel();+ char error[512];+ bool warmed = cbm_ui_assets_warm(NULL, error, sizeof(error));+ cbm_ui_assets_state_t state = cbm_ui_assets_state();++ cbm_ui_assets_reset_for_testing();+ ui_test_restore_assets_env(old_assets);+ (void)cbm_unlink(pack_path);+ (void)cbm_rmdir(directory);++ ASSERT_FALSE(warmed);+ ASSERT_EQ(state, CBM_UI_ASSETS_CANCELLED);+ PASS();+}++TEST(ui_asset_pack_install_never_follows_a_predictable_temp_symlink) {+#ifdef _WIN32+ SKIP_PLATFORM(+ "Windows reparse-point creation requires privileges; installer contracts cover it");+#else+ static const char sentinel_content[] = "foreign sentinel must survive\n";+ char source_directory[] = "/tmp/cbm_ui_install_source_XXXXXX";+ char install_directory[] = "/tmp/cbm_ui_install_target_XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(source_directory));+ ASSERT_NOT_NULL(cbm_mkdtemp(install_directory));++ size_t pack_length = 0U;+ unsigned char *pack = ui_test_pack(&pack_length, false);+ ASSERT_NOT_NULL(pack);+ char source_pack[1024];+ cbm_ui_assets_reset_for_testing();+ ASSERT_TRUE(ui_test_publish_pack(source_directory, pack, pack_length, source_pack));+ free(pack);++ const char *pack_name = strrchr(source_pack, '/');+ ASSERT_NOT_NULL(pack_name);+ pack_name++;+ char installed_pack[1024];+ char old_temporary[1024];+ char sentinel_path[1024];+ ASSERT_LT(+ snprintf(installed_pack, sizeof(installed_pack), "%s/%s", install_directory, pack_name),+ (int)sizeof(installed_pack));+ ASSERT_LT(snprintf(old_temporary, sizeof(old_temporary), "%s.tmp", installed_pack),+ (int)sizeof(old_temporary));+ ASSERT_LT(snprintf(sentinel_path, sizeof(sentinel_path), "%s/foreign.txt", install_directory),+ (int)sizeof(sentinel_path));+ ASSERT_EQ(th_write_file(sentinel_path, sentinel_content), 0);+ ASSERT_EQ(symlink(sentinel_path, old_temporary), 0);++ char *old_assets = getenv("CBM_UI_ASSETS_DIR") ? strdup(getenv("CBM_UI_ASSETS_DIR")) : NULL;+ ASSERT_EQ(cbm_setenv("CBM_UI_ASSETS_DIR", source_directory, 1), 0);+ char error[512] = {0};+ bool installed = cbm_ui_assets_install(install_directory, false, error, sizeof(error));++ char sentinel_after[sizeof(sentinel_content)] = {0};+ FILE *sentinel_file = cbm_fopen(sentinel_path, "rb");+ size_t sentinel_length =+ sentinel_file ? fread(sentinel_after, 1U, sizeof(sentinel_after), sentinel_file) : 0U;+ bool sentinel_closed = !sentinel_file || fclose(sentinel_file) == 0;+ struct stat old_temp_info;+ bool old_temp_is_still_symlink =+ lstat(old_temporary, &old_temp_info) == 0 && S_ISLNK(old_temp_info.st_mode);+ cbm_path_info_t installed_info;+ bool installed_is_regular = cbm_path_info_utf8(installed_pack, &installed_info) == 0 &&+ installed_info.is_regular && !installed_info.is_symlink;+ bool removed = cbm_ui_assets_remove(install_directory, false, error, sizeof(error));++ cbm_ui_assets_reset_for_testing();+ ui_test_restore_assets_env(old_assets);+ (void)cbm_unlink(old_temporary);+ (void)cbm_unlink(installed_pack);+ (void)cbm_unlink(sentinel_path);+ (void)cbm_unlink(source_pack);+ (void)cbm_rmdir(install_directory);+ (void)cbm_rmdir(source_directory);++ ASSERT_TRUE(installed);+ ASSERT_TRUE(sentinel_closed);+ ASSERT_EQ(sentinel_length, sizeof(sentinel_content) - 1U);+ ASSERT_MEM_EQ(sentinel_after, sentinel_content, sizeof(sentinel_content) - 1U);+ ASSERT_TRUE(old_temp_is_still_symlink);+ ASSERT_TRUE(installed_is_regular);+ ASSERT_TRUE(removed);+ PASS();+#endif+}++TEST(ui_asset_pack_install_remove_is_hash_bound_and_dry_run_safe) {+ char source_directory[] = "/tmp/cbm_ui_lifecycle_source_XXXXXX";+ char install_directory[] = "/tmp/cbm_ui_lifecycle_target_XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(source_directory));+ ASSERT_NOT_NULL(cbm_mkdtemp(install_directory));++ size_t pack_length = 0U;+ unsigned char *pack = ui_test_pack(&pack_length, false);+ ASSERT_NOT_NULL(pack);+ char source_pack[1024];+ cbm_ui_assets_reset_for_testing();+ ASSERT_TRUE(ui_test_publish_pack(source_directory, pack, pack_length, source_pack));+ const char *pack_name = strrchr(source_pack, '/');+ ASSERT_NOT_NULL(pack_name);+ pack_name++;+ char installed_pack[1024];+ ASSERT_LT(+ snprintf(installed_pack, sizeof(installed_pack), "%s/%s", install_directory, pack_name),+ (int)sizeof(installed_pack));++ char *old_assets = getenv("CBM_UI_ASSETS_DIR") ? strdup(getenv("CBM_UI_ASSETS_DIR")) : NULL;+ ASSERT_EQ(cbm_setenv("CBM_UI_ASSETS_DIR", source_directory, 1), 0);+ char error[512] = {0};+ bool dry_install = cbm_ui_assets_install(install_directory, true, error, sizeof(error));+ cbm_path_info_t info;+ bool absent_after_dry_install = cbm_path_info_utf8(installed_pack, &info) != 0;+ bool installed = cbm_ui_assets_install(install_directory, false, error, sizeof(error));++ unsigned char *installed_bytes = malloc(pack_length);+ FILE *installed_file = cbm_fopen(installed_pack, "rb");+ size_t installed_length = installed_file && installed_bytes+ ? fread(installed_bytes, 1U, pack_length, installed_file)+ : 0U;+ bool installed_closed = !installed_file || fclose(installed_file) == 0;+ bool exact_copy = installed_bytes && installed_length == pack_length &&+ memcmp(installed_bytes, pack, pack_length) == 0;+ free(installed_bytes);++ bool dry_remove = cbm_ui_assets_remove(install_directory, true, error, sizeof(error));+ bool present_after_dry_remove = cbm_path_info_utf8(installed_pack, &info) == 0;+ bool removed = cbm_ui_assets_remove(install_directory, false, error, sizeof(error));+ bool absent_after_remove = cbm_path_info_utf8(installed_pack, &info) != 0;++ bool reinstalled = cbm_ui_assets_install(install_directory, false, error, sizeof(error));+ FILE *tampered_file = cbm_fopen(installed_pack, "r+b");+ bool tampered = tampered_file && fseek(tampered_file, -1L, SEEK_END) == 0;+ int original_last_byte = tampered ? fgetc(tampered_file) : EOF;+ tampered = tampered && original_last_byte != EOF && fseek(tampered_file, -1L, SEEK_END) == 0 &&+ fputc(original_last_byte ^ 1, tampered_file) != EOF;+ if (tampered_file && fclose(tampered_file) != 0) {+ tampered = false;+ }+ bool refused_tampered_remove =+ !cbm_ui_assets_remove(install_directory, false, error, sizeof(error));+ bool tampered_preserved = cbm_path_info_utf8(installed_pack, &info) == 0;+ bool preservation_explained = strstr(error, "not owned; preserved") != NULL;++ cbm_ui_assets_reset_for_testing();+ ui_test_restore_assets_env(old_assets);+ (void)cbm_unlink(installed_pack);+ (void)cbm_unlink(source_pack);+ (void)cbm_rmdir(install_directory);+ (void)cbm_rmdir(source_directory);+ free(pack);++ ASSERT_TRUE(dry_install);+ ASSERT_TRUE(absent_after_dry_install);+ ASSERT_TRUE(installed);+ ASSERT_TRUE(installed_closed);+ ASSERT_TRUE(exact_copy);+ ASSERT_TRUE(dry_remove);+ ASSERT_TRUE(present_after_dry_remove);+ ASSERT_TRUE(removed);+ ASSERT_TRUE(absent_after_remove);+ ASSERT_TRUE(reinstalled);+ ASSERT_TRUE(tampered);+ ASSERT_TRUE(refused_tampered_remove);+ ASSERT_TRUE(tampered_preserved);+ ASSERT_TRUE(preservation_explained);+ PASS();+}++TEST(ui_asset_pack_staged_removal_is_owned_and_transactional) {+ char source_directory[] = "/tmp/cbm_ui_staged_remove_source_XXXXXX";+ char install_directory[] = "/tmp/cbm_ui_staged_remove_target_XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(source_directory));+ ASSERT_NOT_NULL(cbm_mkdtemp(install_directory));+ size_t pack_length = 0U;+ unsigned char *pack = ui_test_pack(&pack_length, false);+ ASSERT_NOT_NULL(pack);+ char source_pack[1024];+ cbm_ui_assets_reset_for_testing();+ ASSERT_TRUE(ui_test_publish_pack(source_directory, pack, pack_length, source_pack));+ const char *pack_name = strrchr(source_pack, '/');+ ASSERT_NOT_NULL(pack_name);+ pack_name++;+ char installed_pack[1024];+ ASSERT_LT(+ snprintf(installed_pack, sizeof(installed_pack), "%s/%s", install_directory, pack_name),+ (int)sizeof(installed_pack));+ char *old_assets = getenv("CBM_UI_ASSETS_DIR") ? strdup(getenv("CBM_UI_ASSETS_DIR")) : NULL;+ ASSERT_EQ(cbm_setenv("CBM_UI_ASSETS_DIR", source_directory, 1), 0);+ char error[512] = {0};+ ASSERT_TRUE(cbm_ui_assets_install(install_directory, false, error, sizeof(error)));++ cbm_activation_transaction_t *removal = NULL;+ bool foreign = false;+ bool staged =+ cbm_ui_assets_stage_remove(install_directory, &removal, &foreign, error, sizeof(error));+ ASSERT_TRUE(staged);+ ASSERT_FALSE(foreign);+ ASSERT_NOT_NULL(removal);+ ASSERT_EQ(cbm_activation_transaction_commit(removal, NULL, NULL),+ CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_activation_transaction_finalize(removal), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_EQ(cbm_activation_transaction_close(&removal), CBM_ACTIVATION_TRANSACTION_OK);+ cbm_path_info_t info;+ bool exact_removed = cbm_path_info_utf8(installed_pack, &info) != 0;++ ASSERT_TRUE(cbm_ui_assets_install(install_directory, false, error, sizeof(error)));+ FILE *tampered_file = cbm_fopen(installed_pack, "r+b");+ ASSERT_NOT_NULL(tampered_file);+ ASSERT_EQ(fseek(tampered_file, -1L, SEEK_END), 0);+ int last_byte = fgetc(tampered_file);+ ASSERT_TRUE(last_byte != EOF);+ ASSERT_EQ(fseek(tampered_file, -1L, SEEK_END), 0);+ ASSERT_TRUE(fputc(last_byte ^ 1, tampered_file) != EOF);+ ASSERT_EQ(fclose(tampered_file), 0);+ removal = NULL;+ foreign = false;+ bool foreign_staged =+ cbm_ui_assets_stage_remove(install_directory, &removal, &foreign, error, sizeof(error));+ bool foreign_preserved = cbm_path_info_utf8(installed_pack, &info) == 0;++ cbm_ui_assets_reset_for_testing();+ ui_test_restore_assets_env(old_assets);+ (void)cbm_activation_transaction_close(&removal);+ (void)cbm_unlink(installed_pack);+ (void)cbm_unlink(source_pack);+ (void)cbm_rmdir(install_directory);+ (void)cbm_rmdir(source_directory);+ free(pack);++ ASSERT_TRUE(exact_removed);+ ASSERT_TRUE(foreign_staged);+ ASSERT_TRUE(foreign);+ ASSERT_NULL(removal);+ ASSERT_TRUE(foreign_preserved);+ PASS();+}++/* File identity alone does not detect a truncate/rewrite through an already+ * open handle. Publication must validate the exact bytes at the public name,+ * and removal must validate the exact object after moving it to the private+ * retained name. Both mutations below preserve the inode on POSIX. */+TEST(ui_asset_pack_commit_rejects_in_place_rewrite_after_stage) {+ char source_directory[] = "/tmp/cbm_ui_commit_source_XXXXXX";+ char install_directory[] = "/tmp/cbm_ui_commit_target_XXXXXX";+ ASSERT_NOT_NULL(cbm_mkdtemp(source_directory));+ ASSERT_NOT_NULL(cbm_mkdtemp(install_directory));+ size_t pack_length = 0U;+ unsigned char *pack = ui_test_pack(&pack_length, false);+ ASSERT_NOT_NULL(pack);+ char source_pack[1024];+ cbm_ui_assets_reset_for_testing();+ ASSERT_TRUE(ui_test_publish_pack(source_directory, pack, pack_length, source_pack));+ const char *pack_name = strrchr(source_pack, '/');+ ASSERT_NOT_NULL(pack_name);+ pack_name++;+ char installed_pack[1024];+ ASSERT_LT(+ snprintf(installed_pack, sizeof(installed_pack), "%s/%s", install_directory, pack_name),+ (int)sizeof(installed_pack));+ char *old_assets = getenv("CBM_UI_ASSETS_DIR") ? strdup(getenv("CBM_UI_ASSETS_DIR")) : NULL;+ ASSERT_EQ(cbm_setenv("CBM_UI_ASSETS_DIR", source_directory, 1), 0);+ char error[512] = {0};+ ASSERT_TRUE(cbm_ui_assets_install(install_directory, false, error, sizeof(error)));+ ASSERT_TRUE(cbm_ui_assets_verify_file(installed_pack));++ cbm_activation_transaction_t *publication = NULL;+ ASSERT_TRUE(+ cbm_ui_assets_stage_install(install_directory, &publication, error, sizeof(error)));+ ASSERT_NOT_NULL(publication);+ const char *staged = cbm_activation_transaction_staged_path(publication);+ ASSERT_NOT_NULL(staged);+ FILE *staged_file = cbm_fopen(staged, "r+b");+ ASSERT_NOT_NULL(staged_file);+ ASSERT_EQ(fseek(staged_file, -1L, SEEK_END), 0);+ int staged_last = fgetc(staged_file);+ ASSERT_TRUE(staged_last != EOF);+ ASSERT_EQ(fseek(staged_file, -1L, SEEK_END), 0);+ ASSERT_TRUE(fputc(staged_last ^ 1, staged_file) != EOF);+ ASSERT_EQ(fclose(staged_file), 0);+ ASSERT_EQ(cbm_ui_assets_commit_install(publication),+ CBM_ACTIVATION_TRANSACTION_VALIDATION_FAILED);+ ASSERT_EQ(cbm_activation_transaction_close(&publication), CBM_ACTIVATION_TRANSACTION_OK);+ ASSERT_TRUE(cbm_ui_assets_verify_file(installed_pack));++ cbm_activation_transaction_t *removal = NULL;+ bool foreign = false;+ ASSERT_TRUE(cbm_ui_assets_stage_remove(install_directory, &removal, &foreign, error,+ sizeof(error)));+ ASSERT_FALSE(foreign);+ ASSERT_NOT_NULL(removal);+ FILE *target_file = cbm_fopen(installed_pack, "r+b");+ ASSERT_NOT_NULL(target_file);+ ASSERT_EQ(fseek(target_file, -1L, SEEK_END), 0);+ int target_last = fgetc(target_file);+ ASSERT_TRUE(target_last != EOF);+ ASSERT_EQ(fseek(target_file, -1L, SEEK_END), 0);+ ASSERT_TRUE(fputc(target_last ^ 1, target_file) != EOF);+ ASSERT_EQ(fclose(target_file), 0);+ ASSERT_EQ(cbm_ui_assets_commit_removal(removal),+ CBM_ACTIVATION_TRANSACTION_VALIDATION_FAILED);+ ASSERT_EQ(cbm_activation_transaction_close(&removal), CBM_ACTIVATION_TRANSACTION_OK);+ cbm_path_info_t preserved_info;+ ASSERT_EQ(cbm_path_info_utf8(installed_pack, &preserved_info), 0);+ ASSERT_TRUE(preserved_info.is_regular);+ ASSERT_FALSE(cbm_ui_assets_verify_file(installed_pack));++ cbm_ui_assets_reset_for_testing();+ ui_test_restore_assets_env(old_assets);+ (void)cbm_unlink(installed_pack);+ (void)cbm_unlink(source_pack);+ (void)cbm_rmdir(install_directory);+ (void)cbm_rmdir(source_directory);+ free(pack);PASS();}-TEST(embedded_stub_count) {- /* Stub should have 0 files */- ASSERT_EQ(CBM_EMBEDDED_FILE_COUNT, 0);+TEST(ui_asset_standard_manifest_has_no_capability) {+ cbm_ui_assets_reset_for_testing();+ ASSERT_FALSE(cbm_ui_assets_supported());+ ASSERT_EQ(cbm_ui_assets_state(), CBM_UI_ASSETS_UNAVAILABLE);+ ASSERT_NULL(cbm_ui_asset_lookup("/index.html"));PASS();}@@ -870,9 +1398,16 @@ SUITE(ui) {RUN_TEST(config_corrupt_file);RUN_TEST(config_missing_fields);- /* Embedded assets (stub) */- RUN_TEST(embedded_lookup_not_found);- RUN_TEST(embedded_stub_count);+ /* External UI asset pack */+ RUN_TEST(ui_asset_pack_validates_before_publication);+ RUN_TEST(ui_asset_pack_wrong_hash_fails_closed);+ RUN_TEST(ui_asset_pack_structural_corruption_fails_after_valid_hash);+ RUN_TEST(ui_asset_pack_prestart_cancellation_is_not_lost);+ RUN_TEST(ui_asset_pack_install_never_follows_a_predictable_temp_symlink);+ RUN_TEST(ui_asset_pack_install_remove_is_hash_bound_and_dry_run_safe);+ RUN_TEST(ui_asset_pack_staged_removal_is_owned_and_transactional);+ RUN_TEST(ui_asset_pack_commit_rejects_in_place_rewrite_after_stage);+ RUN_TEST(ui_asset_standard_manifest_has_no_capability);/* Layout engine */RUN_TEST(layout_empty_graph);diff --git a/tests/test_ui_asset_pack_contract.sh b/tests/test_ui_asset_pack_contract.shnew file mode 100644index 000000000..692702701--- /dev/null+++ b/tests/test_ui_asset_pack_contract.sh@@ -0,0 +1,133 @@+#!/usr/bin/env bash+# Contract for the external UI asset pack. The pack deliberately stays+# uncompressed and independently scannable: this is an asset boundary, not an+# attempt to hide frontend bytes from security tooling.+set -euo pipefail++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+WORK="$(mktemp -d "${TMPDIR:-/tmp}/cbm-ui-pack-test.XXXXXX")"+trap 'rm -rf "$WORK"' EXIT++mkdir -p "$WORK/a/assets" "$WORK/b/assets"+printf '%s\n' '<!doctype html><title>Codebase Memory — Graph</title>' > "$WORK/a/index.html"+printf '%s\n' 'console.log("transparent-ui-pack")' > "$WORK/a/assets/app.js"+printf '%s\n' 'body { color: #fff; }' > "$WORK/a/assets/app.css"++# Copy in a deliberately different creation order. Filesystem enumeration,+# mtimes, and source-root names must not affect the output.+cp "$WORK/a/assets/app.css" "$WORK/b/assets/app.css"+cp "$WORK/a/index.html" "$WORK/b/index.html"+cp "$WORK/a/assets/app.js" "$WORK/b/assets/app.js"+touch -t 200101010101 "$WORK/a/index.html"+touch -t 203001010101 "$WORK/b/index.html"++mkdir -p "$WORK/a-out" "$WORK/b-out"+node "$ROOT/scripts/pack-ui-assets.mjs" \+ "$WORK/a" "$WORK/a-out" "$WORK/a-manifest.c"+node "$ROOT/scripts/pack-ui-assets.mjs" \+ "$WORK/b" "$WORK/b-out" "$WORK/b-manifest.c"++PACK_A="$(find "$WORK/a-out" -maxdepth 1 -type f -name 'cbm-ui-*.pack')"+PACK_B="$(find "$WORK/b-out" -maxdepth 1 -type f -name 'cbm-ui-*.pack')"+[ -n "$PACK_A" ] && [ -n "$PACK_B" ]+[ "$(basename "$PACK_A")" = "$(basename "$PACK_B")" ]+cmp "$PACK_A" "$PACK_B"+cmp "$WORK/a-manifest.c" "$WORK/b-manifest.c"++python3 - "$PACK_A" "$WORK/a-manifest.c" <<'PY'+from __future__ import annotations++import hashlib+import pathlib+import re+import struct+import sys++pack_path = pathlib.Path(sys.argv[1])+manifest_path = pathlib.Path(sys.argv[2])+data = pack_path.read_bytes()+manifest = manifest_path.read_text(encoding="utf-8")++(+ magic,+ version,+ header_bytes,+ flags,+ count,+ entry_bytes,+ index_offset,+ index_size,+ paths_offset,+ paths_size,+ payload_offset,+ payload_size,+ total_size,+) = struct.unpack_from("<8sHHIIIQQQQQQQ", data, 0)+assert magic == b"CBMUIPK\0", "wrong pack magic"+assert version == 1+assert header_bytes == 80+assert flags == 0+assert count == 3+assert entry_bytes == 24+assert index_offset == 80+assert index_size == count * entry_bytes+assert paths_offset == index_offset + index_size+assert payload_offset == paths_offset + paths_size+assert payload_size == len(data) - payload_offset+assert total_size == len(data)++cursor = index_offset+entries = []+for _ in range(count):+ path_offset, path_len, mime_id, cache_id, offset, length = struct.unpack_from(+ "<IHBBQQ", data, cursor+ )+ cursor += 24+ path = data[+ paths_offset + path_offset:paths_offset + path_offset + path_len+ ].decode("ascii")+ entries.append((path, path_offset, path_len, mime_id, cache_id, offset, length))++assert cursor == paths_offset+assert [entry[0] for entry in entries] == [+ "/assets/app.css", "/assets/app.js", "/index.html"+]+assert [entry[3] for entry in entries] == [3, 2, 1]+assert [entry[4] for entry in entries] == [2, 2, 1]++path_cursor = 0+for path, path_offset, path_len, *_rest in entries:+ assert path_offset == path_cursor, f"non-contiguous path table for {path}"+ path_cursor += path_len+assert path_cursor == paths_size++payload_cursor = 0+for path, _path_offset, _path_len, _mime, _cache, offset, length in entries:+ assert offset == payload_cursor, f"non-contiguous payload for {path}"+ payload_cursor += length+assert payload_cursor == payload_size++# The bytes remain visible to scanners and SBOM/license tooling. Compression+# or encoding would make this assertion fail.+assert b"transparent-ui-pack" in data+assert b"<!doctype html>" in data++digest = hashlib.sha256(data).hexdigest()+assert re.search(rf'CBM_UI_ASSET_SHA256\[\]\s*=\s*"{digest}"', manifest)+assert re.search(rf"CBM_UI_ASSET_SIZE\s*=\s*UINT64_C\({len(data)}\)", manifest)+assert re.search(+ rf'CBM_UI_ASSET_PACK_NAME\[\]\s*=\s*"cbm-ui-{digest}\.pack"', manifest+)+assert pack_path.name == f"cbm-ui-{digest}.pack"+PY++# A source symlink makes the build depend on bytes outside the declared dist+# tree. It is rejected rather than followed or silently omitted.+ln -s ../index.html "$WORK/a/assets/linked.html"+if node "$ROOT/scripts/pack-ui-assets.mjs" \+ "$WORK/a" "$WORK/a-out" "$WORK/rejected.c" 2>/dev/null; then+ echo "FAIL: UI pack generator accepted a symlink" >&2+ exit 1+fi++echo "PASS: deterministic, transparent, hash-bound UI asset pack"diff --git a/tests/test_vendored_integrity_contract.sh b/tests/test_vendored_integrity_contract.shnew file mode 100644index 000000000..c39768527--- /dev/null+++ b/tests/test_vendored_integrity_contract.sh@@ -0,0 +1,42 @@+#!/usr/bin/env bash+# Contract: every vendored input is content-pinned, including opaque blobs and+# the generated Tree-sitter sources that are compiled into release binaries.++set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+FIXTURE="$(mktemp -d "${TMPDIR:-/tmp}/cbm-vendored-integrity.XXXXXX")"+trap 'rm -rf "$FIXTURE"' EXIT++fail() {+ echo "FAIL: $*" >&2+ exit 1+}++make_fixture() {+ local destination="$1"+ mkdir -p "$destination/scripts" "$destination/vendored/yyjson"+ cp "$ROOT/scripts/security-vendored.sh" "$destination/scripts/security-vendored.sh"+ : > "$destination/vendored/yyjson/safe.c"+ printf '%s %s\n' \+ 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' \+ 'vendored/yyjson/safe.c' > "$destination/scripts/vendored-checksums.txt"+}++opaque="$FIXTURE/opaque"+make_fixture "$opaque"+printf '\230\237\000\000opaque-vector-bytes\n' > "$opaque/vendored/yyjson/code_vectors.bin"+if (cd "$opaque" && bash scripts/security-vendored.sh >/dev/null 2>&1); then+ fail "vendored integrity gate accepted an unmanifested opaque binary blob"+fi++grammar="$FIXTURE/grammar"+make_fixture "$grammar"+mkdir -p "$grammar/internal/cbm/vendored/grammars/example"+printf '%s\n' 'int tree_sitter_example(void) { return 1; }' \+ > "$grammar/internal/cbm/vendored/grammars/example/parser.c"+if (cd "$grammar" && bash scripts/security-vendored.sh >/dev/null 2>&1); then+ fail "vendored integrity gate accepted an unmanifested generated grammar source"+fi++echo "vendored integrity contract: OK"diff --git a/tests/test_venue_parity_contract.sh b/tests/test_venue_parity_contract.shindex 11cac18da..48c4ea2ef 100755--- a/tests/test_venue_parity_contract.sh+++ b/tests/test_venue_parity_contract.sh@@ -99,7 +99,7 @@ ALLOWED_CMDS = {"gh", "python3", "node", "codesign", "xcrun", "command", "awk",}# Per-file additions: _build.yml packages artifacts (make/strip are packaging-# steps, not test legs) and drives npm for the embedded UI; release.yml pushes finished artifacts to registries after+# steps, not test legs) and drives npm for the UI build; release.yml pushes finished artifacts to registries after# every product-exercising gate already ran; the brew tap smoke installs the# released formula.ALLOWED_EXTRA = {diff --git a/tests/test_vm_worktree_manifest.sh b/tests/test_vm_worktree_manifest.shindex d858c2737..9dcfc81c8 100644--- a/tests/test_vm_worktree_manifest.sh+++ b/tests/test_vm_worktree_manifest.sh@@ -60,6 +60,26 @@ if ! grep -Fq -- '-c \"set -e -o pipefail; $*\"' "$driver"; thenecho "FAIL: Windows VM remote shell must propagate pipeline failures" >&2exit 1fi+if grep -Fq 'cd $VM_REPO && git apply' <<<"$sync_block" ||+ grep -Fq 'cd $VM_REPO && tar -xf' <<<"$sync_block"; then+ echo "FAIL: Windows VM sync must expand the selected checkout locally before transport" >&2+ exit 1+fi+if ! grep -Fq "cd '\$VM_REPO' && git apply" <<<"$sync_block" ||+ ! grep -Fq "cd '\$VM_REPO' && tar -xf" <<<"$sync_block"; then+ echo "FAIL: Windows VM sync patch and manifest must target the selected checkout" >&2+ exit 1+fi+if ! grep -Fq 'CBM_CI_RUN_ID" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$' "$driver"; then+ echo "FAIL: Windows VM run ids must be validated before remote path interpolation" >&2+ exit 1+fi+preflight_block="$(sed -n '/^vm_preflight() {$/,/^}$/p' "$driver")"+if grep -Fq 'C:\\cbm\\scripts\\ci' <<<"$preflight_block" ||+ [ "$(grep -c 'VM_REPO_WIN' <<<"$preflight_block")" -lt 2 ]; then+ echo "FAIL: Windows VM preflight must use the selected per-run checkout" >&2+ exit 1+fiif ! grep -Fq 'tests/test_vm_worktree_manifest.sh' "$ROOT/scripts/test.sh"; thenecho "FAIL: Windows VM sync contract is not wired into the test suite" >&2exit 1@@ -116,7 +136,7 @@ if ! grep -Fq "JOBS='\$(nproc)'" "$provisioner" ||exit 1figuards_block="$(sed -n '/^guards)/,/^ ;;/p' "$driver")"-# The guards leg builds the CI-shaped product binary (embedded UI) into an+# The guards leg builds the CI-shaped UI product and its external pack into an# isolated BUILD_DIR, then hands that artifact to the maintained# PowerShell driver through a plain cmd shell (CI's environment shape, not# the MSYS2 login shell whose TMP ancestry the daemon correctly refuses).@@ -128,6 +148,11 @@ if ! grep -Fq 'scripts/build.sh --with-ui CC=clang CXX=clang++ SANITIZE= BUILD_Decho "FAIL: Windows VM guards must delegate to the maintained native-Windows driver" >&2exit 1fi+if ! grep -Fq 'cd /d ${VM_REPO_WIN}' <<<"$guards_block" ||+ grep -Fq 'cd /d C:\\cbm' <<<"$guards_block"; then+ echo "FAIL: Windows VM guards must run against the selected per-run checkout" >&2+ exit 1+fiif grep -Fq 'for g in tests/windows/test_*.py' <<<"$guards_block"; thenecho "FAIL: Windows VM guards must not duplicate the native-Windows driver loop" >&2exit 1diff --git a/tests/test_vt_gate_zero_tolerance_contract.sh b/tests/test_vt_gate_zero_tolerance_contract.shindex fb5d2177f..f7c29a340 100644--- a/tests/test_vt_gate_zero_tolerance_contract.sh+++ b/tests/test_vt_gate_zero_tolerance_contract.sh@@ -1,15 +1,7 @@#!/usr/bin/env bash-# Contract: the VirusTotal release gate (scripts/ci/check-virustotal.sh) is-# ZERO tolerance — ANY detection on ANY artifact blocks, with no version-# carve-out, no engine carve-out, and no evidence side-channel.-#-# A tolerance path existed briefly (single-engine Microsoft "!ml" on-# pre-releases, endpoint-evidence-gated) and was deliberately reverted: the-# project does not ship binaries carrying a VirusTotal detection, full stop.-# False positives are resolved upstream (Microsoft FP submission for the exact-# hashes, then re-run the verify job — no rebuild), never by loosening the-# gate. This contract pins that decision against a stubbed VT API so a future-# "just tolerate this one heuristic" change has to consciously delete it.+# Contract: the VT gate is an exact-set, content-bound, minimum-engine,+# zero-tolerance gate. Empty, partial, duplicate, unexpected or malformed+# action output fails before a release can be described as scanned.set -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"@@ -18,97 +10,256 @@ FIX="$(mktemp -d "${TMPDIR:-/tmp}/vt-gate-contract.XXXXXX")"trap 'rm -rf "$FIX"' EXITfail() { echo "FAIL: $*" >&2; exit 1; }+hash_file() {+ sha256sum "$1" 2>/dev/null | awk '{print $1}' || shasum -a 256 "$1" | awk '{print $1}'+}-# Tripwire for the specific reverted mechanism (behavioral checks below are-# the real contract; these names only catch that exact machinery returning).-for needle in defender-endpoint-verification av-endpoint-verify; do+for needle in defender-endpoint-verification av-endpoint-verify false-positive false_positive; doif grep -q "$needle" "$GATE"; then- fail "gate references '$needle' — the reverted evidence side-channel is back"+ fail "gate references reverted/tolerance machinery '$needle'"fidone-mkdir -p "$FIX/bin" "$FIX/work/binaries" "$FIX/responses"+mkdir -p "$FIX/bin" "$FIX/work/binaries/objects" "$FIX/responses"+printf 'release-bytes\n' > "$FIX/work/binaries/objects/probe"+printf 'second-object\n' > "$FIX/work/binaries/objects/probe2"+PROBE_SHA="$(hash_file "$FIX/work/binaries/objects/probe")"+PROBE2_SHA="$(hash_file "$FIX/work/binaries/objects/probe2")"+PROBE_SIZE="$(wc -c < "$FIX/work/binaries/objects/probe" | tr -d ' ')"+PROBE2_SIZE="$(wc -c < "$FIX/work/binaries/objects/probe2" | tr -d ' ')"++write_manifest() { # one|two+ local count=1 associations=3+ if [ "$1" = "two" ]; then count=2; associations=4; fi+ {+ echo '# cbm-release-scan-set-v1'+ echo "# scan_objects=$count"+ echo "# associations=$associations"+ printf 'scan_path\tsha256\tsize\tassociation_count\tassociation_kinds\n'+ printf 'objects/probe\t%s\t%s\t3\tarchive,binary,runtime\n' "$PROBE_SHA" "$PROBE_SIZE"+ if [ "$1" = "two" ]; then+ printf 'objects/probe2\t%s\t%s\t1\tarchive\n' "$PROBE2_SHA" "$PROBE2_SIZE"+ fi+ } > "$FIX/work/binaries/scan-set.tsv"+ {+ echo '# cbm-release-scan-associations-v2'+ echo "# associations=$associations"+ echo "# scan_objects=$count"+ printf 'association_type\tarchive\tarchive_sha256\tvariant\tkind\tmember\tasset_path\tmime\tscan_path\tobject_sha256\tsize\n'+ printf 'archive\tprobe.tar.gz\t%s\tstandard\tarchive\t\t\t\tobjects/probe\t%s\t%s\n' "$PROBE_SHA" "$PROBE_SHA" "$PROBE_SIZE"+ printf 'member\tprobe.tar.gz\t%s\tstandard\tbinary\tcodebase-memory-mcp\t\t\tobjects/probe\t%s\t%s\n' "$PROBE_SHA" "$PROBE_SHA" "$PROBE_SIZE"+ printf 'member\tprobe.tar.gz\t%s\tstandard\truntime\tLICENSE\t\t\tobjects/probe\t%s\t%s\n' "$PROBE_SHA" "$PROBE_SHA" "$PROBE_SIZE"+ if [ "$1" = "two" ]; then+ printf 'archive\tprobe2.zip\t%s\tstandard\tarchive\t\t\t\tobjects/probe2\t%s\t%s\n' "$PROBE2_SHA" "$PROBE2_SHA" "$PROBE2_SIZE"+ fi+ } > "$FIX/work/binaries/associations.tsv"+}+write_manifest one-# curl stub: serve the canned VT analysis JSON selected by the id in the URL.+# curl stub: serve canned analysis JSON selected by the ID in the API URL.cat > "$FIX/bin/curl" <<'EOF'#!/usr/bin/env bashurl="${@: -1}"id="${url##*/analyses/}"-resp="$STUB_RESPONSES/$id.json"-[ -f "$resp" ] || exit 22-cat "$resp"+response="$STUB_RESPONSES/$id.json"+[ -f "$response" ] || exit 22+cat "$response"EOFchmod +x "$FIX/bin/curl"-mk_response() { # id malicious suspicious+write_response() { # id malicious suspicious undetected sha sizecat > "$FIX/responses/$1.json" <<EOF-{"data":{"attributes":{"status":"completed",- "stats":{"malicious":$2,"suspicious":$3,"undetected":60,"harmless":0}}}}+{"meta":{"file_info":{"sha256":"$5","size":$6}},+ "data":{"id":"$1","type":"analysis","attributes":{"status":"completed",+ "stats":{"malicious":$2,"suspicious":$3,"undetected":$4,"harmless":0,+ "timeout":0,"confirmed-timeout":0,"failure":0,"type-unsupported":0},+ "results":{"Microsoft":{"category":"undetected","result":null,+ "engine_version":"1.26070","engine_update":"20260808"}}}}}EOF}-mk_response clean 0 0-mk_response one_malicious 1 0-mk_response one_suspicious 0 1--# Same detection as one_malicious, but carrying the per-engine results a real-# analysis returns. Pins that the gate NAMES the engine that fired.-cat > "$FIX/responses/named_engine.json" <<'EOF'-{"data":{"attributes":{"status":"completed",- "stats":{"malicious":1,"suspicious":0,"undetected":60,"harmless":0},- "results":{- "Microsoft":{"category":"malicious","result":"Trojan:Win32/Wacatac.B!ml",- "engine_version":"1.1.24010.10","engine_update":"20260807"},- "Kaspersky":{"category":"undetected","result":null,- "engine_version":"22.0.1.28","engine_update":"20260807"}- }}}}+write_response clean-analysis 0 0 60 "$PROBE_SHA" "$PROBE_SIZE"+write_response clean-analysis-2 0 0 60 "$PROBE2_SHA" "$PROBE2_SIZE"+write_response one-malicious 1 0 59 "$PROBE_SHA" "$PROBE_SIZE"+write_response one-suspicious 0 1 59 "$PROBE_SHA" "$PROBE_SIZE"+write_response low-engines 0 0 49 "$PROBE_SHA" "$PROBE_SIZE"+write_response wrong-hash 0 0 60 "$PROBE2_SHA" "$PROBE_SIZE"+write_response wrong-size 0 0 60 "$PROBE_SHA" "$((PROBE_SIZE + 1))"++cat > "$FIX/responses/named-engine.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"id":"named-engine","type":"analysis","attributes":{"status":"completed",+ "stats":{"malicious":1,"suspicious":0,"undetected":59,"harmless":0,+ "timeout":0,"confirmed-timeout":0,"failure":0,"type-unsupported":0},+ "results":{+ "Microsoft":{"category":"malicious","result":"Trojan:Script/Wacatac.B!ml",+ "engine_version":"1.26070","engine_update":"20260808"},+ "Kaspersky":{"category":"undetected","result":null,+ "engine_version":"22","engine_update":"20260808"}+ }}}}+EOF++cat > "$FIX/responses/malformed-stats.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"id":"malformed-stats","attributes":{"status":"completed",+ "stats":{"malicious":"0","suspicious":0,"undetected":60,"harmless":0}}}}+EOF++cat > "$FIX/responses/missing-analysis-id.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"type":"analysis","attributes":{"status":"completed",+ "stats":{"malicious":0,"suspicious":0,"undetected":60,"harmless":0,+ "timeout":0,"confirmed-timeout":0,"failure":0,"type-unsupported":0},+ "results":{"Microsoft":{"category":"undetected","result":null,+ "engine_version":"1.26070","engine_update":"20260808"}}}}}+EOF++cat > "$FIX/responses/missing-microsoft.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"id":"missing-microsoft","type":"analysis","attributes":{"status":"completed",+ "stats":{"malicious":0,"suspicious":0,"undetected":60,"harmless":0,+ "timeout":0,"confirmed-timeout":0,"failure":0,"type-unsupported":0},+ "results":{"Kaspersky":{"category":"undetected","result":null,+ "engine_version":"22","engine_update":"20260808"}}}}}+EOF++cat > "$FIX/responses/microsoft-timeout.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"id":"microsoft-timeout","type":"analysis","attributes":{"status":"completed",+ "stats":{"malicious":0,"suspicious":0,"undetected":59,"harmless":0,"timeout":1,+ "confirmed-timeout":0,"failure":0,"type-unsupported":0},+ "results":{"Microsoft":{"category":"timeout","result":null,+ "engine_version":"1.26070","engine_update":"20260808"}}}}}+EOF++cat > "$FIX/responses/wrong-response-type.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"id":"wrong-response-type","type":"file","attributes":{"status":"completed",+ "stats":{"malicious":0,"suspicious":0,"undetected":60,"harmless":0,+ "timeout":0,"confirmed-timeout":0,"failure":0,"type-unsupported":0},+ "results":{"Microsoft":{"category":"undetected","result":null,+ "engine_version":"1.26070","engine_update":"20260808"}}}}}+EOF++cat > "$FIX/responses/missing-malicious-stat.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"id":"missing-malicious-stat","type":"analysis","attributes":{"status":"completed",+ "stats":{"suspicious":0,"undetected":60,"harmless":0,"timeout":0,+ "confirmed-timeout":0,"failure":0,"type-unsupported":0},+ "results":{"Microsoft":{"category":"undetected","result":null,+ "engine_version":"1.26070","engine_update":"20260808"}}}}}+EOF++cat > "$FIX/responses/detail-aggregate-mismatch.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"id":"detail-aggregate-mismatch","type":"analysis","attributes":{"status":"completed",+ "stats":{"malicious":0,"suspicious":0,"undetected":60,"harmless":0,+ "timeout":0,"confirmed-timeout":0,"failure":0,"type-unsupported":0},+ "results":{"Microsoft":{"category":"undetected","result":null,+ "engine_version":"1.26070","engine_update":"20260808"},+ "ContradictoryEngine":{"category":"malicious","result":"Example.Test",+ "engine_version":"1","engine_update":"20260808"}}}}}+EOF++cat > "$FIX/responses/malformed-microsoft-evidence.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"id":"malformed-microsoft-evidence","type":"analysis","attributes":{"status":"completed",+ "stats":{"malicious":0,"suspicious":0,"undetected":60,"harmless":0,"timeout":0,+ "confirmed-timeout":0,"failure":0,"type-unsupported":0},+ "results":{"Microsoft":{"category":"undetected","result":null,+ "engine_version":{},"engine_update":"20260808"}}}}}EOF-echo "release-bytes" > "$FIX/work/binaries/probe"+url_for() { printf 'https://www.virustotal.com/gui/file-analysis/%s/detection' "$1"; }-run_gate() { # version analysis-id -> echoes exit code- rm -f /tmp/vt_gate_fail+run_gate() { # action-output -> prints rc+ rm -f "$FIX/work/binaries/vt-results.tsv" "$FIX/last.log"local rc=0(cd "$FIX/work" &&PATH="$FIX/bin:$PATH" \STUB_RESPONSES="$FIX/responses" \- VT_API_KEY="stub" \- VERSION="$1" \- VT_ANALYSIS="binaries/probe=https://www.virustotal.com/gui/file-analysis/$2/detection" \- bash "$GATE" >"$FIX/last.log" 2>&1) || rc=$?+ VT_API_KEY=stub \+ VT_ANALYSIS="$1" \+ VT_EXPECTED_SCAN_SET=binaries/scan-set.tsv \+ VT_ASSOCIATIONS=binaries/associations.tsv \+ VT_RESULTS_PATH=binaries/vt-results.tsv \+ VT_REQUEST_INTERVAL_SECONDS=0 \+ VT_POLL_TIMEOUT_SECONDS=2 \+ VT_CURL_TIMEOUT_SECONDS=1 \+ MIN_ENGINES=50 \+ bash "$GATE" > "$FIX/last.log" 2>&1) || rc=$?echo "$rc"}-[ "$(run_gate v0.9.1 clean)" = "0" ] || fail "clean scan must pass"+clean_output="binaries/objects/probe=$(url_for clean-analysis)"+[ "$(run_gate "$clean_output")" = "0" ] || fail "clean exact scan must pass: $(cat "$FIX/last.log")"+RESULTS="$FIX/work/binaries/vt-results.tsv"+[ -f "$RESULTS" ] || fail "clean gate did not atomically publish its results manifest"+grep -q '^# cbm-virustotal-results-v1$' "$RESULTS" || fail "results marker missing"+grep -q "objects/probe.*$PROBE_SHA.*$PROBE_SIZE.*60" "$RESULTS" || \+ fail "results do not bind path/hash/size/actual engine count"-for version in v0.9.1 v0.9.1-rc.1 v0.9.1-pre1 v1.0.0-alpha.1; do- [ "$(run_gate "$version" one_malicious)" != "0" ] || \- fail "1 malicious must block on $version (pre-release carve-outs are gone)"- [ "$(run_gate "$version" one_suspicious)" != "0" ] || \- fail "1 suspicious must block on $version"+for id in one-malicious one-suspicious; do+ [ "$(run_gate "binaries/objects/probe=$(url_for "$id")")" != "0" ] || \+ fail "$id must block"done+[ "$(run_gate "binaries/objects/probe=$(url_for low-engines)")" != "0" ] || \+ fail "completed analysis below the 50-engine policy must block"+grep -q 'only 49/49 decisive engines' "$FIX/last.log" || fail "low-engine failure is not explicit"-# A detection must NAME the engine that fired.-#-# The gate reported counts only ("1 malicious / 59 engines"), which is the one-# thing a reader cannot act on: a false-positive submission goes to a SPECIFIC-# vendor (and the WDSI developer path is a web form, so there is no API to guess-# with), and triage starts with "known-noisy engine, or a new family?". In the-# 2026-08-07 dry run three artifacts flagged and the logs could not say by what,-# so the answer had to be fetched by hand from the web UI afterwards.-[ "$(run_gate v0.9.1 named_engine)" != "0" ] || fail "named-engine detection must still block"-grep -q "Microsoft" "$FIX/last.log" || \- fail "gate must name the flagging engine (Microsoft) — got: $(cat "$FIX/last.log")"-grep -q "Trojan:Win32/Wacatac.B!ml" "$FIX/last.log" || \- fail "gate must report the detection label, not just the vendor"-# Engines that did NOT flag must not be listed, or the actionable line drowns.-if grep -q "detected by: Kaspersky" "$FIX/last.log"; then- fail "gate listed a non-flagging engine (Kaspersky) as a detection"+[ "$(run_gate "binaries/objects/probe=$(url_for named-engine)")" != "0" ] || \+ fail "named-engine detection must block"+grep -q 'Microsoft = Trojan:Script/Wacatac.B!ml' "$FIX/last.log" || \+ fail "gate must report the flagging engine and label"+grep -q $'objects/probe\t.*\t1\t0\t' "$FIX/work/binaries/vt-results.tsv" || \+ fail "blocked completed-set counts were not preserved as workflow evidence"+if grep -q 'detected by: Kaspersky' "$FIX/last.log"; then+ fail "gate listed a non-flagging engine as a detection"fi-# Naming engines must not weaken the gate: an analysis WITHOUT per-engine-# results still blocks on the counts alone.-[ "$(run_gate v0.9.1 one_malicious)" != "0" ] || \- fail "detection without engine detail must still block"+for id in wrong-hash wrong-size malformed-stats missing-analysis-id missing-microsoft microsoft-timeout wrong-response-type missing-malicious-stat detail-aggregate-mismatch malformed-microsoft-evidence; do+ [ "$(run_gate "binaries/objects/probe=$(url_for "$id")")" != "0" ] || \+ fail "$id response must fail closed"+done+++# The independently validated association rows, not a mutable summary cell,+# decide whether an object is executable and therefore requires Microsoft.+write_manifest one+sed -i.bak 's/archive,binary,runtime/archive,runtime/' "$FIX/work/binaries/scan-set.tsv"+rm -f "$FIX/work/binaries/scan-set.tsv.bak"+[ "$(run_gate "$clean_output")" != "0" ] || \+ fail "scan-set kinds that contradict association rows must block"+grep -q 'association kinds differ' "$FIX/last.log" || fail "kind mismatch is not diagnosable"+write_manifest one++# Exact TSV schemas reject surplus cells instead of allowing DictReader to+# hide them under its implicit None key.+printf '\textra-cell\n' >> "$FIX/work/binaries/scan-set.tsv"+[ "$(run_gate "$clean_output")" != "0" ] || fail "surplus scan-set cells must block"+write_manifest one++# The action output itself is part of the gate. It must be a bijection with the+# expected set before any per-analysis verdict can matter.+write_manifest two+two_output="binaries/objects/probe=$(url_for clean-analysis),binaries/objects/probe2=$(url_for clean-analysis-2)"+[ "$(run_gate "$two_output")" = "0" ] || fail "two-object exact set must pass: $(cat "$FIX/last.log")"+[ "$(run_gate "binaries/objects/probe=$(url_for clean-analysis)")" != "0" ] || \+ fail "partial action output must block"+[ "$(run_gate "$two_output,binaries/objects/probe=$(url_for one-malicious)")" != "0" ] || \+ fail "duplicate action path must block"+[ "$(run_gate "$two_output,binaries/objects/unexpected=$(url_for one-malicious)")" != "0" ] || \+ fail "unexpected action path must block"+[ "$(run_gate "binaries/objects/probe")" != "0" ] || fail "malformed action entry must block"+[ "$(run_gate "binaries/objects/probe=$(url_for clean-analysis),")" != "0" ] || \+ fail "empty action entry must block"+[ "$(run_gate "binaries/objects/probe=$(url_for clean-analysis),binaries/objects/probe2=$(url_for clean-analysis)")" != "0" ] || \+ fail "one analysis URL reused for two objects must block"++# Local bytes are rehashed immediately before matching action output, so a+# post-extraction mutation cannot inherit the original clean result.+write_manifest one+printf 'tampered\n' > "$FIX/work/binaries/objects/probe"+[ "$(run_gate "$clean_output")" != "0" ] || fail "tampered staged object must block before polling"+grep -q 'changed after extraction' "$FIX/last.log" || fail "tamper failure is not diagnosable"-rm -f /tmp/vt_gate_fail-echo "PASS: VT gate is zero tolerance and names the engine that fired"+echo 'PASS: VT gate is exact-set, content-bound, >=50-engine and zero tolerance'diff --git a/tests/test_vt_release_notes_contract.sh b/tests/test_vt_release_notes_contract.shnew file mode 100644index 000000000..3488fa9bb--- /dev/null+++ b/tests/test_vt_release_notes_contract.sh@@ -0,0 +1,169 @@+#!/usr/bin/env bash+# Contract for idempotent, evidence-bound VirusTotal release-note publication.+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+SCRIPT="$ROOT/scripts/ci/append-vt-notes.sh"+PUBLISH="$ROOT/scripts/ci/publish-vt-evidence.sh"+FIX="$(mktemp -d "${TMPDIR:-/tmp}/vt-notes-contract.XXXXXX")"+trap 'rm -rf "$FIX"' EXIT+fail() { echo "FAIL: $*" >&2; exit 1; }++mkdir -p "$FIX/bin" "$FIX/binaries"+SHA_A='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+SHA_B='bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'+cat > "$FIX/binaries/associations.tsv" <<EOF+# cbm-release-scan-associations-v2+# archives=1+# binaries=1+# packs=0+# runtime_files=0+# pack_assets=1+# associations=3+# scan_objects=2+association_type archive archive_sha256 variant kind member asset_path mime scan_path object_sha256 size+archive codebase-memory-mcp-linux-amd64.tar.gz $SHA_A standard archive objects/archive $SHA_A 100+member codebase-memory-mcp-linux-amd64.tar.gz $SHA_A standard binary codebase-memory-mcp objects/archive $SHA_A 100+pack_asset codebase-memory-mcp-linux-amd64.tar.gz $SHA_A ui ui_asset cbm-ui-$SHA_B.pack /assets/app.js application/javascript objects/script $SHA_B 20+EOF+cat > "$FIX/binaries/vt-results.tsv" <<EOF+# cbm-virustotal-results-v1+# scan_objects=2+# associations=3+# min_engines_policy=50+# min_completed_engines=59+# max_completed_engines=61+scan_path sha256 size association_count completed_engines total_engines malicious suspicious analysis_id microsoft_category microsoft_engine_version microsoft_engine_update virustotal_url+objects/archive $SHA_A 100 2 59 62 0 0 analysis-a undetected 1.26070 20260808 https://www.virustotal.com/gui/file/$SHA_A/detection+objects/script $SHA_B 20 1 61 64 0 0 analysis-b https://www.virustotal.com/gui/file/$SHA_B/detection+EOF+cat > "$FIX/current.md" <<'EOF'+Intro text.++<!-- cbm-security-verification:start -->+## Security Verification++stale data+<!-- cbm-security-verification:end -->++Outro text.+EOF++cat > "$FIX/bin/gh" <<'EOF'+#!/usr/bin/env bash+set -euo pipefail+if [ "$1" = release ] && [ "$2" = view ]; then+ cat "$STUB_RELEASE_BODY"+ exit 0+fi+if [ "$1" = release ] && [ "$2" = edit ]; then+ while [ "$#" -gt 0 ]; do+ if [ "$1" = --notes-file ]; then+ cp "$2" "$STUB_CAPTURE"+ exit 0+ fi+ shift+ done+fi+if [ "$1" = release ] && [ "$2" = upload ]; then+ shift 3 # release upload <tag>+ while [ "$#" -gt 0 ]; do+ case "$1" in+ --clobber) shift ;;+ --repo) shift 2 ;;+ *) cp "$1" "$STUB_UPLOAD_DIR/$(basename "$1")"; shift ;;+ esac+ done+ exit 0+fi+exit 2+EOF+chmod +x "$FIX/bin/gh"++run_notes() { # current capture+ (cd "$FIX" &&+ PATH="$FIX/bin:$PATH" \+ GH_TOKEN=stub \+ VERSION=v1.0.0 \+ GITHUB_REPOSITORY=DeusData/codebase-memory-mcp \+ VT_ASSOCIATIONS=binaries/associations.tsv \+ VT_RESULTS_PATH=binaries/vt-results.tsv \+ STUB_RELEASE_BODY="$1" \+ STUB_CAPTURE="$2" \+ bash "$SCRIPT")+}++run_notes "$FIX/current.md" "$FIX/first.md"+[ "$(grep -c 'cbm-security-verification:start' "$FIX/first.md")" = 1 ] || fail "start marker duplicated"+[ "$(grep -c 'cbm-security-verification:end' "$FIX/first.md")" = 1 ] || fail "end marker duplicated"+grep -q 'Intro text.' "$FIX/first.md" || fail "content before marked section was lost"+grep -q 'Outro text.' "$FIX/first.md" || fail "content after marked section was lost"+! grep -q 'stale data' "$FIX/first.md" || fail "stale marked section was appended instead of replaced"+grep -q '2 distinct byte objects' "$FIX/first.md" || fail "unique-object scope missing"+grep -q '3 exact release associations' "$FIX/first.md" || fail "association scope missing"+grep -q '59–61 decisive engine results' "$FIX/first.md" || fail "measured engine range missing"+grep -q 'Microsoft returned a decisive clean verdict for all 1 executable objects' "$FIX/first.md" || \+ fail "executable Microsoft coverage is not stated"+grep -q "$SHA_A" "$FIX/first.md" || fail "full archive SHA-256 missing"+grep -q "gui/file/$SHA_A/detection" "$FIX/first.md" || fail "archive VirusTotal link missing"+for asset in virustotal-associations.tsv virustotal-scan-set.tsv virustotal-results.tsv virustotal-evidence-checksums.txt; do+ grep -q "releases/download/v1.0.0/$asset" "$FIX/first.md" || fail "public evidence link missing: $asset"+done+! grep -q '70+' "$FIX/first.md" || fail "unmeasured engine claim returned"++run_notes "$FIX/first.md" "$FIX/second.md"+cmp -s "$FIX/first.md" "$FIX/second.md" || fail "marked release-note update is not idempotent"++cp "$FIX/binaries/vt-results.tsv" "$FIX/binaries/vt-results.clean.tsv"+printf '\textra-cell\n' >> "$FIX/binaries/vt-results.tsv"+if run_notes "$FIX/current.md" "$FIX/surplus-capture.md"; then+ fail "surplus result TSV cells must fail closed"+fi+mv "$FIX/binaries/vt-results.clean.tsv" "$FIX/binaries/vt-results.tsv"++cat > "$FIX/reversed.md" <<'EOF'+Intro text.++<!-- cbm-security-verification:end -->+stale reversed data+<!-- cbm-security-verification:start -->+EOF+if run_notes "$FIX/reversed.md" "$FIX/reversed-capture.md"; then+ fail "reversed verification markers must fail closed"+fi++mkdir -p "$FIX/public"+run_publish() {+ (cd "$FIX" &&+ PATH="$FIX/bin:$PATH" \+ GH_TOKEN=stub \+ VERSION=v1.0.0 \+ GITHUB_REPOSITORY=DeusData/codebase-memory-mcp \+ VT_ASSOCIATIONS=binaries/associations.tsv \+ VT_EXPECTED_SCAN_SET=binaries/scan-set.tsv \+ VT_RESULTS_PATH=binaries/vt-results.tsv \+ STUB_UPLOAD_DIR="$FIX/public" \+ bash "$PUBLISH")+}+cat > "$FIX/binaries/scan-set.tsv" <<EOF+# cbm-release-scan-set-v1+# scan_objects=2+# associations=3+scan_path sha256 size association_count association_kinds+objects/archive $SHA_A 100 2 archive,binary+objects/script $SHA_B 20 1 ui_asset+EOF+run_publish+for asset in virustotal-associations.tsv virustotal-scan-set.tsv virustotal-results.tsv virustotal-evidence-checksums.txt; do+ [ -s "$FIX/public/$asset" ] || fail "public evidence asset was not uploaded: $asset"+done+[ "$(wc -l < "$FIX/public/virustotal-evidence-checksums.txt" | tr -d ' ')" = 3 ] || \+ fail "public evidence checksum inventory is incomplete"+cp "$FIX/binaries/scan-set.tsv" "$FIX/binaries/scan-set.clean.tsv"+sed '1s/cbm-release-scan-set-v1/wrong-marker/' "$FIX/binaries/scan-set.clean.tsv" > "$FIX/binaries/scan-set.tsv"+if run_publish; then+ fail "public evidence publication must reject a wrong scan-set marker"+fi+mv "$FIX/binaries/scan-set.clean.tsv" "$FIX/binaries/scan-set.tsv"++echo 'PASS: VT release evidence is durable, scoped, measured, full-hash and idempotent'diff --git a/tests/test_windows_bundle_contract.sh b/tests/test_windows_bundle_contract.shindex 6942245d5..5acb8b9d5 100644--- a/tests/test_windows_bundle_contract.sh+++ b/tests/test_windows_bundle_contract.sh@@ -1,5 +1,6 @@#!/usr/bin/env bash-# INVERTED release-surface contract: Windows ships ONE binary.+# INVERTED release-surface contract: Windows ships ONE executable plus its+# authenticated runtime assets.## History this guards against. The Windows release used to be a PAIR — a small# permanent launcher (codebase-memory-mcp.exe) plus the real product binary@@ -7,18 +8,15 @@# reason: a running .exe cannot replace its own image on Windows, so an# in-process self-update needs a second resident binary to do the swap.#-# That stub is statically indistinguishable from a dropper — a small unsigned-# PE whose whole job is verify-and-execute another binary — and Defender's ML-# scored it Trojan:Win32/Wacatac.B!ml on x64 regardless of what we changed-# (bcrypt-free, stripped, VERSIONINFO'd and even resource-free builds were all-# flagged), while the product binary itself scans clean on every platform.+# That stub was a small unsigned PE whose whole job was verify-and-execute+# another binary: unnecessary loader-like behavior and a second artifact to+# audit. Historical variants received Microsoft Wacatac verdicts, but those+# observations did not expose a stable feature or prove classifier causation.#-# The fix removed the stub and moved self-update OUT of the process into-# install.ps1, which runs while CBM is NOT running. So this file asserts the-# ABSENCE of the flagged design, plus the one step that replaces it:-# install.ps1 must RETIRE the running binary (rename it out of the way) before-# publishing the new one — losing that step silently breaks every Windows-# update.+# The fix removed the stub. The downloaded candidate now owns the complete+# runtime-set transaction under the native activation guard; install.ps1 only+# verifies/extracts and invokes it. In particular, the script must never retire+# the old executable or publish sidecars ahead of the guarded transaction.## The non-launcher release/security assertions from the previous contract# (VM-driver hardening, archive allowlists, HTTPS-only downloads, profile-rooted@@ -82,21 +80,25 @@ payload = "codebase-memory-mcp.payload.exe"windows_archive_names = (binary, "cbm-integrations.json", "LICENSE", "install.ps1", "THIRD_PARTY_NOTICES.md",)+ui_pack_pattern = r"cbm-ui-[0-9a-f]{64}\.pack"-# ── 1. The archive is exactly five files, defined in ONE place ───────────────+# ── 1. Standard is five files; UI adds exactly one root pack ────────────────# Every venue (release build, local artifact-flow smoke) produces archives# through scripts/package-release.sh, so the layout is asserted where it is# defined and cannot fork per venue.package_release = read("scripts/package-release.sh")-zip_call = re.search(- r"zip -q \"\$OUT_DIR/\$NAME\.zip\" \\\n(?P<members>(?:.|\n)*?)\n", package_release+member_blocks = re.findall(+ r"ARCHIVE_MEMBERS=\(\s*(?P<members>.*?)\s*\)", package_release, re.DOTALL)-require(zip_call is not None, "package-release.sh must build the Windows zip in one zip call")-zip_members = zip_call.group("members").split() if zip_call else []+normalized_member_blocks = [block.split() for block in member_blocks]require(- zip_members == list(windows_archive_names),- "package-release.sh must archive EXACTLY "- f"{' '.join(windows_archive_names)} (found: {' '.join(zip_members) or 'nothing'})",+ list(windows_archive_names) in normalized_member_blocks,+ "package-release.sh must define the exact five-member Windows standard archive",+)+require(+ package_release.count('ARCHIVE_MEMBERS+=("$UI_PACK_NAME")') == 2+ and "^cbm-ui-[0-9a-f]{64}\\.pack$" in package_release,+ "package-release.sh must append exactly one hash-shaped root pack only to UI archives",)# ── 2. No shipped surface may name the payload or build a launcher ───────────@@ -122,8 +124,8 @@ for relative in shipped_surfaces:for marker in launcher_markers:require(marker not in source,- f"{relative} must not reference '{marker}': Windows ships ONE binary and the "- "launcher stub is what Defender flagged as Trojan:Win32/Wacatac.B!ml",+ f"{relative} must not reference '{marker}': Windows ships one executable and the "+ "retired launcher/payload split must not return",)# The stub sources themselves must stay deleted, and the build must not carry a@@ -146,7 +148,7 @@ require()# Each archive variant is still produced through the ONE canonical packaging-# entry, so the four-file layout above governs all of them.+# entry, so the five-or-six-file layout above governs all of them.build_workflow = read(".github/workflows/_build.yml")for archive, call, ui in (("codebase-memory-mcp-windows-amd64.zip", "scripts/package-release.sh windows amd64", False),@@ -163,12 +165,7 @@ for archive, call, ui in (f"_build.yml must produce {archive} via the canonical packaging entry ('{call}')",)-# ── 3. install.ps1 retires the running binary before publishing ──────────────-# This is THE step that replaces the launcher. Windows keeps an image lock on a-# running .exe: it cannot be overwritten, but it CAN be renamed out of the way.-# install.ps1 runs while CBM is not running, renames the installed binary to-# "<dest>.retired-<timestamp>", then installs over the freed name. Without the-# retire step every Windows update fails on a locked destination.+# ── 3. install.ps1 delegates every runtime mutation to the candidate ─────────installer = read("install.ps1")# Windows PowerShell 5.1 decodes a BOM-less .ps1 as ANSI, so a UTF-8 em-dash# arrives as three cp1252 characters ending in a double quote. Inside a string@@ -183,43 +180,76 @@ require(+ ", ".join(f"U+{ord(ch):04X}" for ch in non_ascii)+ ")",)+publish_index = installer.find("& $DownloadedBinary @InstallArgs")require(- "$Dest = Join-Path $InstallDir $BinName" in installer,- "install.ps1 must resolve the canonical install destination as $Dest",+ publish_index >= 0,+ "install.ps1 must invoke the downloaded candidate's native install command",)-retire_match = re.search(- r"if \(Test-Path -LiteralPath \$Dest -PathType Leaf\) \{(?P<body>(?:.|\n)*?)\n\}\n",- installer,+require(+ "& $DownloadedBinary --version" in installer+ and "& $DownloadedBinary @InstallArgs" in installer,+ "install.ps1 must verify and install through the downloaded binary",)-retire = retire_match.group("body") if retire_match else ""require(- retire_match is not None- and re.search(r"\$retired\s*=\s*\"\$Dest\.retired-", retire) is not None- and "Move-Item -LiteralPath $Dest -Destination $retired" in retire,- "install.ps1 must RETIRE the running binary (Move-Item $Dest -> $retired) before "- "publishing the new one — a running .exe cannot be overwritten in place",+ "Move-Item -LiteralPath $Dest" not in installer+ and ".retired-" not in installer+ and "& $Dest daemon stop" not in installer,+ "install.ps1 must not retire, delete, or stop the installed executable before candidate install",)require(- retire_match is not None and "$renamed" in retire and "exit 1" in retire,- "install.ps1 must fail loudly when the running binary cannot be retired",+ "Publish-CbmSidecarAtomically" not in installer+ and "$AssetDest" not in installer+ and "$packDestination" not in installer+ and 'Get-ChildItem -LiteralPath $InstallDir -Filter "cbm-ui-*.pack"' not in installer,+ "install.ps1 must not publish or garbage-collect runtime sidecars outside the native guard",)-publish_index = installer.find("& $DownloadedBinary @InstallArgs")++# The download workspace is recursively deleted on every exit path, so the+# installer must create it itself and must never adopt an existing name. Bind+# the reservation to this directory specifically; the updater-file publisher+# below has a separate exclusive-sibling helper.+temp_dir_factory = re.search(+ r"function\s+New-CbmExclusiveTempDirectory\s*\{(?P<body>.*?)\n\}\s*\n\s*# Detect variant",+ installer,+ re.DOTALL,+)+temp_dir_body = temp_dir_factory.group("body") if temp_dir_factory else ""require(- publish_index > (retire_match.start() if retire_match else -1) >= 0,- "install.ps1 must retire BEFORE it publishes the downloaded binary",+ temp_dir_factory is not None+ and '[guid]::NewGuid().ToString("N")' in temp_dir_body+ and "for ($attempt = 0; $attempt -lt 32; $attempt++)" in temp_dir_body+ and "New-Item -ItemType Directory -Path $candidate -ErrorAction Stop" in temp_dir_body+ and "catch [System.IO.IOException]" in temp_dir_body+ and re.search(r"New-Item[^\n]*-Force", temp_dir_body) is None+ and "Remove-Item" not in temp_dir_body+ and "Test-Path" not in temp_dir_body,+ "install.ps1 must reserve a high-entropy temporary directory exclusively with bounded "+ "collision retries, never adopt or pre-clean an existing path",)require(- "& $DownloadedBinary --version" in installer- and "& $DownloadedBinary @InstallArgs" in installer,- "install.ps1 must verify and install through the downloaded binary",+ "$TmpDir = New-CbmExclusiveTempDirectory -ParentDirectory "+ "([System.IO.Path]::GetTempPath())" in installer+ and '"cbm-install-$(Get-Random)"' not in installer+ and "New-Item -ItemType Directory -Path $TmpDir -Force" not in installer,+ "install.ps1 must clean up only the temporary directory it successfully reserved",+)++# Bind validation to the opened handle, including its exact 64-bit size. A+# raced replacement with a valid prefix plus trailing data must be rejected.+asset_pack = read("src/ui/asset_pack.c")+require(+ "handle_info.nFileSizeHigh" in asset_pack+ and "handle_info.nFileSizeLow" in asset_pack+ and re.search(r"handle_size\s*==\s*expected", asset_pack) is not None,+ "Windows UI pack validation must compare the opened handle's 64-bit size to the manifest",)# ── 4. Package-manager shims resolve the single Windows binary ───────────────single_binary_contracts = {"pkg/npm/install.js": (r"const\s+WINDOWS_BINARY_NAME\s*=\s*['\"]codebase-memory-mcp\.exe['\"]",- r"installWindowsBinaryAtomically\(",- r"windowsBinaryReady\(",+ r"publishRuntimeSetWithRecovery\(",+ r"runtimeSetReady\(",),"pkg/npm/bin.js": (r"binName\s*=\s*isWindows\s*\?\s*['\"]codebase-memory-mcp\.exe['\"]",@@ -227,7 +257,8 @@ single_binary_contracts = {),"pkg/pypi/src/codebase_memory_mcp/_cli.py": (r"_WINDOWS_BINARY_NAME\s*=\s*['\"]codebase-memory-mcp\.exe['\"]",- r"def\s+_windows_binary_ready\(",+ r"def\s+_runtime_set_ready\(",+ r"def\s+_publish_runtime_set\(",),}for relative, patterns in single_binary_contracts.items():@@ -241,18 +272,21 @@ for relative, patterns in single_binary_contracts.items():f"{relative} must remain portable and not own managed launcher state",)-# All package downloaders parse the Windows archive against the exact official-# four-root-file allowlist; they may not silently ignore an attacker-controlled-# fifth member.+# All package downloaders parse the Windows archive against an exact official+# root allowlist; direct install.ps1 additionally distinguishes standard from+# UI by the single hash-shaped pack.exact_archive_guards = {"install.ps1": (- "$seen.Count -ne $WindowsArchiveNames.Count",+ "$seen.Count -ne $expectedArchiveCount",+ "$uiPackCount -ne $expectedUiPackCount",+ "$UiPackPattern",'"LICENSE"','"install.ps1"',"THIRD_PARTY_NOTICES.md",),"pkg/npm/install.js": (- "$seen.Count -ne $requiredNames.Count",+ "seen.size !== expectedCount",+ "UI_PACK_PATTERN","WINDOWS_BINARY_NAME","'LICENSE'","'install.ps1'",@@ -260,7 +294,8 @@ exact_archive_guards = {),"pkg/pypi/src/codebase_memory_mcp/_cli.py": ("name not in required_set",- "len(seen) != len(required)",+ "len(seen) != expected_count",+ "_UI_PACK_RE","_WINDOWS_BINARY_NAME",'"LICENSE"','"install.ps1"',@@ -271,7 +306,7 @@ for relative, needles in exact_archive_guards.items():source = read(relative)require(all(needle in source for needle in needles),- f"{relative} must reject every Windows zip namespace except the official four-file "+ f"{relative} must reject every Windows zip namespace except its official exact ""allowlist",)@@ -556,7 +591,7 @@ require("cmd.exe",)-# ── 8. Release smoke stays profile-rooted and single-binary ──────────────────+# ── 8. Release smoke stays profile-rooted and one-executable ─────────────────smoke_workflow = read(".github/workflows/_smoke.yml")windows_match = re.search(r"(?ms)^ smoke-windows:\s*(.*?)(?=^ [A-Za-z0-9_-]+:\s*$|\Z)", smoke_workflow@@ -607,7 +642,7 @@ require('"$LAUNCH_DIR/codebase-memory-mcp.exe" --version',)),- "Windows release version checks must execute the single binary beneath the current "+ "Windows release version checks must execute the runtime set's one executable beneath the current ""account profile",)# RUNNER_TEMP is legitimate ONLY for artifact provisioning/scanning; every@@ -644,7 +679,7 @@ require('scripts/security-install.sh "$SECURITY_DIR/codebase-memory-mcp.exe"',)),- "Windows release install audit must execute the single binary beneath the current "+ "Windows release install audit must execute the runtime set's one executable beneath the current ""account profile",)@@ -652,8 +687,11 @@ require(smoke_script = read("scripts/smoke-test.sh")require('copy_smoke_binary "$FAKE_HOME/.local/bin/codebase-memory-mcp.exe"' not in smoke_script- and 'copy_smoke_binary "$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe"' not in smoke_script,- "Windows smoke must leave canonical targets absent for an authenticated install",+ and 'copy_smoke_binary "$UPDATE_HOME/.local/bin/codebase-memory-mcp.exe"' in smoke_script+ and 'cp "$SMOKE_UI_PACK" "$(dirname "$destination")/$(basename "$SMOKE_UI_PACK")"'+ in smoke_script,+ "Windows smoke must leave the authenticated-install target absent while staging the complete "+ "binary-plus-pack runtime set for the explicit update fixture",)require("smoke_mktemp_file" in smoke_script@@ -682,7 +720,7 @@ require('HOME="$WIN_HOME" TEMP="$WIN_HOME" TMP="$WIN_HOME"' in smoke_scriptand "MSYS2_ARG_CONV_EXCL='*'" in smoke_scriptand "powershell.exe -NoProfile -ExecutionPolicy Bypass -File" in smoke_script- and '"$WIN_SCRIPT" "--dir=$WIN_DIR"' in smoke_script+ and '"$WIN_SCRIPT" "$DL_VARIANT_ARG" "--dir=$WIN_DIR"' in smoke_scriptand "& $args[1]" not in smoke_script,"Windows install.ps1 smoke must pass native HOME/TEMP/TMP and execute the script directly",)@@ -810,10 +848,10 @@ if pr_windows_blocks:)if failures:- print("Windows single-binary bundle contract FAILED:", file=sys.stderr)+ print("Windows one-executable runtime-set contract FAILED:", file=sys.stderr)for failure in failures:print(f" - {failure}", file=sys.stderr)raise SystemExit(1)-print("Windows single-binary bundle contract passed")+print("Windows one-executable runtime-set contract passed")PYdiff --git a/tests/windows/test_non_ascii_path.py b/tests/windows/test_non_ascii_path.pyindex 4635a3665..e82ea9d64 100644--- a/tests/windows/test_non_ascii_path.py+++ b/tests/windows/test_non_ascii_path.py@@ -1,4 +1,4 @@-"""GREEN regression guard — non-ASCII repo paths keep all definitions on Windows.+"""GREEN regression guard — non-ASCII runtime and repo paths work on Windows.Guards the fix for issue #636 / #357 (landed on main via #700) at the productsurface (real codebase-memory-mcp process, real SQLite DB, real stdio). Two@@ -17,8 +17,8 @@ code page, so a non-ASCII path could not be opened and the parser receivednothing. #700 routed the per-pass reads through cbm_fopen (→ _wfopen with a widepath, src/foundation/compat_fs.c), so non-ASCII paths now parse identically.-This guard fails (red) if that fix regresses. It also passes on Linux/macOS-(byte-transparent UTF-8 filesystem).+This Windows guard also exercises native runtime publication beyond legacy+MAX_PATH; it fails (red) if either path contract regresses.Exit code: 0 == invariant holds (green), 1 == invariant violated (regression),2 == environment/setup error.@@ -29,6 +29,7 @@ Usage:import jsonimport osimport shutil+import subprocessimport sysimport tempfile@@ -62,6 +63,204 @@ NON_ASCII_SEGMENTS = {}+def windows_extended_path(path):+ """Return a Python/Win32 path that is independent of LongPathsEnabled."""+ absolute = os.path.abspath(path).replace("/", "\\")+ if absolute.startswith("\\\\?\\"):+ return absolute+ if absolute.startswith("\\\\"):+ return "\\\\?\\UNC\\" + absolute[2:]+ return "\\\\?\\" + absolute+++def run_product(argv, cwd, env, timeout=120):+ options = {+ "cwd": cwd,+ "env": env,+ "stdout": subprocess.PIPE,+ "stderr": subprocess.STDOUT,+ "text": True,+ "timeout": timeout,+ }+ # With lpApplicationName=NULL, CreateProcess applies the legacy MAX_PATH+ # limit while deriving the module name from the command line. Python's+ # explicit `executable` argument fills lpApplicationName, allowing the+ # extended path to reach the product exactly as a native launcher would.+ if os.name == "nt" and argv and argv[0].startswith("\\\\?\\"):+ options["executable"] = argv[0]+ return subprocess.run(argv, **options)+++def verify_relocated_runtime(binary, work):+ """Probe relocation, then install/probe/uninstall beyond legacy MAX_PATH.++ This binds Windows self-discovery to GetModuleFileNameW: both the hidden+ probe and a process launched from an extended-length path must find the+ adjacent integration/UI assets without an ANSI-code-page fallback or an+ environment override. The real install sequence also binds target+ existence checks: after a secure first install, the target is rewritten in+ place and a non-force `--no` install must preserve those exact bytes.+ """+ source_dir = os.path.dirname(binary)+ runtime_dir = os.path.join(work, "café_日本語_runtime")+ os.makedirs(runtime_dir, exist_ok=True)+ relocated = os.path.join(runtime_dir, os.path.basename(binary))+ shutil.copy2(binary, relocated)++ integration = os.path.join(source_dir, "cbm-integrations.json")+ if not os.path.isfile(integration):+ return "setup: source runtime is missing cbm-integrations.json"+ shutil.copy2(integration, os.path.join(runtime_dir, "cbm-integrations.json"))+ packs = []+ for name in os.listdir(source_dir):+ if name.startswith("cbm-ui-") and name.endswith(".pack"):+ source = os.path.join(source_dir, name)+ if os.path.isfile(source):+ shutil.copy2(source, os.path.join(runtime_dir, name))+ packs.append(name)++ env = os.environ.copy()+ env.pop("CBM_ASSETS_DIR", None)+ env.pop("CBM_UI_ASSETS_DIR", None)+ env["HOME"] = os.path.join(work, "runtime_home")+ env["USERPROFILE"] = env["HOME"]+ env["APPDATA"] = os.path.join(work, "runtime_appdata")+ env["LOCALAPPDATA"] = os.path.join(work, "runtime_localappdata")+ env["XDG_CONFIG_HOME"] = os.path.join(work, "runtime_xdg_config")+ env["XDG_CACHE_HOME"] = os.path.join(work, "runtime_xdg_cache")+ env["XDG_DATA_HOME"] = os.path.join(work, "runtime_xdg_data")+ env["CBM_CACHE_DIR"] = os.path.join(work, "runtime_cache")+ for inherited_config in (+ "CLAUDE_CONFIG_DIR", "CODEX_HOME", "COPILOT_HOME",+ "CRUSH_GLOBAL_CONFIG", "OPENCLAW_CONFIG_PATH", "OPENCLAW_HOME",+ "OPENCLAW_PROFILE", "OPENCLAW_STATE_DIR", "OPENCLAW_WORKSPACE_DIR",+ "OPENCODE_CONFIG", "OPENCODE_CONFIG_DIR", "VIBE_HOME"):+ env.pop(inherited_config, None)+ for directory in (+ env["HOME"], env["APPDATA"], env["LOCALAPPDATA"],+ env["XDG_CONFIG_HOME"], env["XDG_CACHE_HOME"],+ env["XDG_DATA_HOME"], env["CBM_CACHE_DIR"]):+ os.makedirs(directory, exist_ok=True)++ def stop_runtime_daemon():+ try:+ first = run_product(+ [relocated, "daemon", "stop"], runtime_dir, env, timeout=30)+ second = run_product(+ [relocated, "daemon", "stop"], runtime_dir, env, timeout=30)+ return first.returncode == 0 and second.returncode == 0+ except (OSError, subprocess.TimeoutExpired):+ return False++ def fail(message):+ stop_runtime_daemon()+ return message++ probe = run_product([relocated, "--verify-runtime-assets"], runtime_dir, env)+ if probe.returncode != 0:+ return fail("runtime probe rc=%d output=%r packs=%r" % (+ probe.returncode, probe.stdout[-800:], packs))++ # Keep every component below the per-component limit while making the+ # complete UTF-16 path decisively longer than legacy MAX_PATH. The product,+ # not Python, creates this tree during the first real install.+ target = os.path.join(+ work,+ "install_Ωμέγα",+ *("segment_%02d_%s" % (i, "x" * 32) for i in range(7)),+ "bin",+ )+ installed = os.path.join(target, "codebase-memory-mcp.exe")+ if len(os.path.abspath(installed)) <= 260:+ return fail("setup: intended long install path is only %d characters" % len(+ os.path.abspath(installed)))++ first_install = run_product(+ [relocated, "install", "--force", "--skip-config", "--yes",+ "--dir=" + target],+ runtime_dir,+ env,+ )+ if first_install.returncode != 0:+ return fail("long-path install rc=%d output=%r path_len=%d" % (+ first_install.returncode,+ first_install.stdout[-1200:],+ len(os.path.abspath(installed)),+ ))++ installed_extended = windows_extended_path(installed)+ if not os.path.isfile(installed_extended):+ return fail("long-path install did not publish %r" % installed)+ integration_installed = os.path.join(target, "cbm-integrations.json")+ if not os.path.isfile(windows_extended_path(integration_installed)):+ return fail("long-path install omitted cbm-integrations.json")+ for name in packs:+ if not os.path.isfile(windows_extended_path(os.path.join(target, name))):+ return fail("long-path install omitted UI pack %s" % name)++ installed_probe = run_product(+ [installed_extended, "--verify-runtime-assets"], runtime_dir, env)+ if installed_probe.returncode != 0:+ return fail("installed long-path probe rc=%d output=%r" % (+ installed_probe.returncode, installed_probe.stdout[-1200:]))++ # Preserve the file identity/owner/DACL created by the native transaction,+ # but make the bytes visibly foreign. A UTF-8-aware existence check sees+ # this target and honors --no; the legacy narrow stat() treated it as absent+ # and silently replaced it.+ sentinel = b"cbm-long-path-existing-target-must-be-preserved\n"+ with open(installed_extended, "wb") as stream:+ stream.write(sentinel)+ keep = run_product(+ [relocated, "install", "--skip-config", "--no", "--dir=" + target],+ runtime_dir,+ env,+ )+ if keep.returncode != 0:+ return fail("long-path non-force install rc=%d output=%r" % (+ keep.returncode, keep.stdout[-1200:]))+ with open(installed_extended, "rb") as stream:+ retained = stream.read()+ if retained != sentinel:+ return fail("long-path existing target was overwritten despite --no "+ "(target existence probe is not extended-path safe)")++ restore = run_product(+ [relocated, "install", "--force", "--skip-config", "--yes",+ "--dir=" + target],+ runtime_dir,+ env,+ )+ if restore.returncode != 0:+ return fail("long-path restore install rc=%d output=%r" % (+ restore.returncode, restore.stdout[-1200:]))+ restored_probe = run_product(+ [installed_extended, "--verify-runtime-assets"], runtime_dir, env)+ if restored_probe.returncode != 0:+ return fail("restored long-path probe rc=%d output=%r" % (+ restored_probe.returncode, restored_probe.stdout[-1200:]))+ if not stop_runtime_daemon():+ return fail("could not retire the isolated daemon before uninstall")++ uninstall = run_product(+ [installed_extended, "uninstall", "--yes", "--dir=" + target],+ runtime_dir,+ env,+ )+ if uninstall.returncode != 0:+ return fail("long-path uninstall rc=%d output=%r" % (+ uninstall.returncode, uninstall.stdout[-1200:]))+ if os.path.exists(installed_extended):+ return fail("long-path uninstall retained the installed executable")+ if os.path.exists(windows_extended_path(integration_installed)):+ return fail("long-path uninstall retained owned integration assets")+ for name in packs:+ if os.path.exists(windows_extended_path(os.path.join(target, name))):+ return fail("long-path uninstall retained owned UI pack %s" % name)+ stop_runtime_daemon()+ return None++def make_fixture(root):src = os.path.join(root, "src")os.makedirs(src, exist_ok=True)@@ -119,7 +318,16 @@ def main():work = tempfile.mkdtemp(prefix="cbm_win_nonascii_")failures = []+ runtime_error = Nonetry:+ runtime_error = verify_relocated_runtime(binary, work)+ if runtime_error:+ print("[FAIL] non-ASCII runtime relocation: %s" % runtime_error)+ print("\nREGRESSION (red): Unicode/extended-length runtime publication "+ "or exact adjacent-asset resolution failed.")+ return 1+ print("[PASS] Unicode relocation + extended-length install/probe/uninstall")+ascii_repo = os.path.join(work, "ascii_repo")make_fixture(ascii_repo)base = index_and_count(binary, ascii_repo, os.path.join(work, "c_ascii"))@@ -152,14 +360,15 @@ def main():shutil.rmtree(work, ignore_errors=True)if failures:- print("\nREGRESSION (red): %d/%d non-ASCII path variants lost "+ print("\nREGRESSION (red): %d/%d non-ASCII repo path variants lost ""definitions: %s" %(len(failures), len(NON_ASCII_SEGMENTS), ", ".join(failures)))print("Invariant violated: byte-identical fixtures under non-ASCII paths ""must extract the same definitions as the ASCII baseline (fixed by ""#700 — has the cbm_fopen routing in the pass readers regressed?).")return 1- print("\nGREEN: all non-ASCII path variants matched the ASCII baseline.")+ print("\nGREEN: Unicode/extended-length runtime operations passed and all "+ "non-ASCII repo variants matched the ASCII baseline.")return 0diff --git a/tests/windows/test_windows_update_handoff.py b/tests/windows/test_windows_update_handoff.pyindex 48155add3..b0b36a6f4 100644--- a/tests/windows/test_windows_update_handoff.py+++ b/tests/windows/test_windows_update_handoff.py@@ -1,14 +1,15 @@"""GREEN native-Windows guard for the `update` -> install.ps1 handoff.-Windows ships ONE binary, exactly like Linux and macOS: ``codebase-memory-mcp.exe``.+Windows ships one executable in its runtime set, exactly like Linux and macOS:+``codebase-memory-mcp.exe``.There used to be a second, permanently resident launcher stub whose only jobwas to swap the product binary out from under itself, because a running .exe-cannot replace its own image on Windows. Defender's ML scored that stub-Trojan:Win32/Wacatac.B!ml on x64 no matter what the build changed (bcrypt-free,-stripped, versioned and resource-free variants were all flagged), while the-product binary itself scans clean everywhere. So the swap moved OUT of the-process into install.ps1, which runs while CBM is NOT running.+cannot replace its own image on Windows. Historical variants of that stub+received Microsoft Wacatac verdicts. Those observations did not expose a+stable feature or prove causation, but the stub remained unnecessary loader-+like behavior and a second artifact to audit. The swap therefore moved OUT of+the process into install.ps1, which runs while CBM is NOT running.This guard asserts the replacement contract on real native Windows:@@ -20,8 +21,8 @@ This guard asserts the replacement contract on real native Windows:hole.* ``update`` does not disturb an already-open MCP/daemon session.-A regression here means the in-process self-update — and therefore the-AV-flagged launcher stub — came back.+A regression here means the in-process self-update and removed launcher stub+came back.Exit code: 0 == contract honored, 1 == regression, 2 == precondition failure.