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
feat(release): ship one archive set and tolerate a single Microsoft !ml verdict
Martin Vogela4336dc40aa4
diff --git a/.github/workflows/dry-run.yml b/.github/workflows/dry-run.ymlindex 14f20df83..bf7800a53 100644--- a/.github/workflows/dry-run.yml+++ b/.github/workflows/dry-run.yml@@ -151,11 +151,9 @@ jobs:- name: Extract archive artifactsrun: |scripts/ci/extract-release-archives.sh "$RUNNER_TEMP/release-archives" binaries \- --archive-scope=ui \--expect-archives=8 \--expect-binaries=8 \- --expect-packs=8 \- --expect-runtime-files=32+ --expect-runtime-files=24- name: VirusTotal scanuses: crazy-max/ghaction-virustotal@936d8c5c00afe97d3d9a1af26d017cfdf26800a2 # v5.0.0diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex a2d806b68..f806737e8 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -216,11 +216,9 @@ jobs:mkdir -p "$ARCHIVE_DIR" binariesgh release download "$VERSION" --dir "$ARCHIVE_DIR" --repo "$GITHUB_REPOSITORY" --pattern '*.tar.gz' --pattern '*.zip'scripts/ci/extract-release-archives.sh "$ARCHIVE_DIR" binaries \- --archive-scope=ui \--expect-archives=8 \--expect-binaries=8 \- --expect-packs=8 \- --expect-runtime-files=32+ --expect-runtime-files=24- name: Security audits on all unique extracted release objectsrun: |diff --git a/README.md b/README.mdindex 520b95b3b..639c81048 100644--- a/README.md+++ b/README.md@@ -25,7 +25,7 @@ High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-si<p align="center"><img src="docs/graph-ui-screenshot.png" alt="Graph visualization UI showing the codebase-memory-mcp knowledge graph" width="800"><br>- <em>Built-in 3D graph visualization (UI variant) — explore your knowledge graph at localhost:9749</em>+ <em>Built-in 3D graph visualization — explore your knowledge graph at localhost:9749</em></p>## Why codebase-memory-mcp@@ -35,7 +35,7 @@ High-quality parsing through [tree-sitter](https://tree-sitter.github.io/tree-si- **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.-- **Built-in graph visualization** — 3D interactive UI at `localhost:9749` (optional UI binary variant).+- **Built-in graph visualization** — 3D interactive UI at `localhost:9749`, served from the binary itself.- **Infrastructure-as-code indexing** — Dockerfiles, Kubernetes manifests, and Kustomize overlays indexed as graph nodes with cross-references. `Resource` nodes for K8s kinds, `Module` nodes for Kustomize overlays with `IMPORTS` edges to referenced resources.- **15 MCP tools** — search, trace, architecture, impact analysis, targeted index-coverage checks, Cypher queries, dead code detection, cross-service HTTP linking, ADR management, and more.@@ -48,7 +48,7 @@ curl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/iWith graph visualization UI:```bash-curl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/install.sh | bash -s -- --ui+curl -fsSL https://raw.githubusercontent.com/DeusData/codebase-memory-mcp/main/install.sh | bash```**Windows** (PowerShell):@@ -69,7 +69,7 @@ Unblock-File .\install.ps1> **Note:** If you see a script execution policy error, run `Set-ExecutionPolicy -Scope Process Bypass` first, or invoke with `PowerShell -ExecutionPolicy Bypass -File .\install.ps1`.-Options: `--ui` (graph visualization), `--skip-config` (binary only, no agent setup), `--dir=<path>` (custom location).+Options: `--skip-config` (binary only, no agent setup), `--dir=<path>` (custom location).Restart your coding agent. Say **"Index this project"** — done.@@ -77,8 +77,7 @@ Restart your coding agent. Say **"Index this project"** — done.<summary>Manual install</summary>1. **Download** the archive for your platform from the [latest release](https://github.com/DeusData/codebase-memory-mcp/releases/latest):- - `codebase-memory-mcp-<os>-<arch>.tar.gz` (macOS/Linux) or `.zip` (Windows) — standard- - `codebase-memory-mcp-ui-<os>-<arch>.tar.gz` / `.zip` — with graph visualization+ - `codebase-memory-mcp-<os>-<arch>.tar.gz` (macOS/Linux) or `.zip` (Windows)2. **Extract and install** (each archive includes `install.sh` or `install.ps1`):@@ -126,15 +125,7 @@ The ordinary `cli` mode is intentionally separate: it runs one command locally a### Graph Visualization UI-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>` archive--Then run it:+The graph UI is built into the binary — every install on every channel has it. Then run it:```bashcodebase-memory-mcp --ui=true --port=9749@@ -311,15 +302,15 @@ When you open a memory/performance issue, **attach the `.ndjson` trajectory**### Pre-built Binaries-| Platform | Standard | With Graph UI |-|----------|----------|---------------|-| macOS (Apple Silicon) | `codebase-memory-mcp-darwin-arm64.tar.gz` | `codebase-memory-mcp-ui-darwin-arm64.tar.gz` |-| macOS (Intel) | `codebase-memory-mcp-darwin-amd64.tar.gz` | `codebase-memory-mcp-ui-darwin-amd64.tar.gz` |-| Linux (x86_64) | `codebase-memory-mcp-linux-amd64.tar.gz` | `codebase-memory-mcp-ui-linux-amd64.tar.gz` |-| 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` |+| Platform | Archive |+|----------|---------|+| macOS (Apple Silicon) | `codebase-memory-mcp-darwin-arm64.tar.gz` |+| macOS (Intel) | `codebase-memory-mcp-darwin-amd64.tar.gz` |+| Linux (x86_64) | `codebase-memory-mcp-linux-amd64.tar.gz` |+| Linux (ARM64) | `codebase-memory-mcp-linux-arm64.tar.gz` |+| Windows (x86_64) | `codebase-memory-mcp-windows-amd64.zip` |-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.+Every release includes `checksums.txt` with SHA-256 hashes. The executable is self-contained — no adjacent data file is required. 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`.@@ -377,12 +368,12 @@ You: "Install this MCP server: https://github.com/DeusData/codebase-memory-mcp"```bashgit clone https://github.com/DeusData/codebase-memory-mcp.gitcd codebase-memory-mcp-scripts/build.sh # standard binary-scripts/build.sh --with-ui # with graph visualization+scripts/build.sh --with-ui # the shipped composition (graph UI embedded)+scripts/build.sh # without the UI (development only)# Binary at: build/c/codebase-memory-mcp (codebase-memory-mcp.exe on Windows)```-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.+Every platform ships **one self-contained executable**: the graph UI and the agent integration templates are linked into the binary, so an extracted archive is immediately complete.Run the test suite (6,768 tests across 120 suites):@@ -724,7 +715,7 @@ SQLite databases stored at `~/.cache/codebase-memory-mcp/`. Persists across rest| `trace_path` returns 0 results | Use `search_graph(name_pattern=".*PartialName.*")` first to find the exact name. || Queries return wrong project results | Add `project="name"` parameter. Use `list_projects` to see names. || Binary not found after install | Add to PATH: `export PATH="$HOME/.local/bin:$PATH"` |-| UI not loading | Ensure you downloaded the `ui` variant and ran `--ui=true`. Check `http://localhost:9749`. |+| UI not loading | Ensure you ran `--ui=true`. Check `http://localhost:9749`. |## Hybrid LSPdiff --git a/pkg/go/cmd/codebase-memory-mcp/main.go b/pkg/go/cmd/codebase-memory-mcp/main.goindex 2e7432c87..f0e675720 100644--- a/pkg/go/cmd/codebase-memory-mcp/main.go+++ b/pkg/go/cmd/codebase-memory-mcp/main.go@@ -38,7 +38,6 @@ const (repo = "DeusData/codebase-memory-mcp"version = "0.8.1"windowsBinaryName = "codebase-memory-mcp.exe"- integrationsFileName = "cbm-integrations.json"maxRedirects = 5requestTimeout = 2 * time.Minute@@ -154,7 +153,7 @@ func main() {func ensureBinary() (string, error) {binary := binPath()ready, err := runtimeSetReadyLocked(- filepath.Dir(binary), filepath.Base(binary), runtimeVariant(), verifyCandidate,+ filepath.Dir(binary), filepath.Base(binary), verifyCandidate,)if err != nil {return "", err@@ -170,7 +169,7 @@ func ensureBinary() (string, error) {func binPath() string {return filepath.Join(- cacheDir(), version, runtimeVariant(), binaryNameForOS(runtime.GOOS),+ cacheDir(), version, binaryNameForOS(runtime.GOOS),)}@@ -185,13 +184,6 @@ func executionPathForOS(binary, targetOS string) string {return binary}-func runtimeVariant() string {- if strings.EqualFold(os.Getenv("CBM_VARIANT"), "ui") {- return "ui"- }- return "standard"-}-func printPortableMutationGuidance(args []string) {action := runtimeMutationAction(args)if action != "uninstall" {@@ -361,7 +353,6 @@ func archiveNamesForOS(platform, binaryName string) []string {}return []string{binaryName,- integrationsFileName,"LICENSE",installer,"THIRD_PARTY_NOTICES.md",@@ -371,7 +362,6 @@ func archiveNamesForOS(platform, binaryName string) []string {func download(dest string) error {platform := goos()arch := goarch()- selectedVariant := runtimeVariant()ext := "tar.gz"if platform == "windows" {ext = "zip"@@ -381,13 +371,9 @@ func download(dest string) error {if platform == "linux" {portable = "-portable"}- uiPrefix := ""- if selectedVariant == "ui" {- uiPrefix = "ui-"- }archive := fmt.Sprintf(- "codebase-memory-mcp-%s%s-%s%s.%s",- uiPrefix, platform, arch, portable, ext,+ "codebase-memory-mcp-%s-%s%s.%s",+ 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)@@ -421,19 +407,19 @@ func download(dest string) error {binName := binaryNameForOS(platform)archiveNames := archiveNamesForOS(platform, binName)- extractNames := []string{binName, integrationsFileName}+ extractNames := []string{binName}var runtimeNames []stringif ext == "tar.gz" {runtimeNames, err = extractTarGz(- archivePath, tmp, archiveNames, extractNames, selectedVariant,+ archivePath, tmp, archiveNames, extractNames,)if err != nil {return fmt.Errorf("extraction failed: %w", err)}} else {runtimeNames, err = extractZip(- archivePath, tmp, archiveNames, extractNames, selectedVariant,+ archivePath, tmp, archiveNames, extractNames,)if err != nil {return fmt.Errorf("extraction failed: %w", err)@@ -458,7 +444,7 @@ func download(dest string) error {}if err := publishRuntimeSetWithRecovery(- tmp, filepath.Dir(dest), binName, selectedVariant, verifyCandidate,+ tmp, filepath.Dir(dest), binName, verifyCandidate,); err != nil {return fmt.Errorf("could not install runtime set: %w", err)}@@ -611,81 +597,41 @@ func verifyChecksum(path, expected string) error {return nil}-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- }- digest := strings.TrimSuffix(strings.TrimPrefix(name, prefix), suffix)- if digest != strings.ToLower(digest) {- return false- }- decoded, err := hex.DecodeString(digest)- return err == nil && len(decoded) == sha256.Size-}-func validateArchiveMemberNames(- names, archiveNames []string, variant string, caseInsensitive bool,-) (string, error) {+ names, archiveNames []string, caseInsensitive bool,+) error {required := make(map[string]struct{}, len(archiveNames))for _, name := range archiveNames {required[name] = struct{}{}}seen := make(map[string]struct{}, len(names))found := make(map[string]struct{}, len(archiveNames))- uiPack := ""for _, name := range names {key := nameif caseInsensitive {key = strings.ToLower(name)}if _, exists := seen[key]; exists {- return "", fmt.Errorf(+ return fmt.Errorf("duplicate or case-conflicting archive entry: %q", name,)}seen[key] = struct{}{}- _, isRequired := required[name]- isPack := variant == "ui" && isUIPackName(name)- if !isRequired && !isPack {- return "", fmt.Errorf(+ if _, isRequired := required[name]; !isRequired {+ return fmt.Errorf("archive must contain only the exact root files: %s",strings.Join(archiveNames, ", "),)}- if isPack {- if uiPack != "" {- return "", fmt.Errorf(- "archive must contain exactly one content-addressed UI pack",- )- }- uiPack = name- } else {- found[name] = struct{}{}- }- }- expectedCount := len(archiveNames)- if variant == "ui" {- expectedCount+++ found[name] = struct{}{}}- if len(seen) != expectedCount || len(found) != len(required) ||- (variant == "ui" && uiPack == "") {- return "", fmt.Errorf(+ if len(seen) != len(archiveNames) || len(found) != len(required) {+ return fmt.Errorf("archive must contain exactly one of each required root file: %s",strings.Join(archiveNames, ", "),)}- return uiPack, nil-}--func runtimeArchiveNames(extractNames []string, uiPack string) []string {- result := append([]string(nil), extractNames...)- if uiPack != "" {- result = append(result, uiPack)- }- return result+ return nil}func validateArchiveResourceLimits(limits archiveResourceLimits) error {@@ -837,14 +783,12 @@ func tarGzMemberNamesWithLimits(func extractTarGz(archivePath, destDir string,archiveNames, extractNames []string,- variant string,) ([]string, error) {return extractTarGzWithLimits(archivePath,destDir,archiveNames,extractNames,- variant,defaultArchiveResourceLimits,)}@@ -852,20 +796,17 @@ func extractTarGz(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,- )+ err := validateArchiveMemberNames(names, archiveNames, false)if err != nil {return nil, err}- runtimeNames := runtimeArchiveNames(extractNames, uiPack)+ runtimeNames := append([]string(nil), extractNames...)targets := make(map[string]struct{}, len(runtimeNames))for _, name := range runtimeNames {targets[name] = struct{}{}@@ -948,14 +889,12 @@ func extractTarGzWithLimits(func extractZip(archivePath, destDir string,archiveNames, extractNames []string,- variant string,) ([]string, error) {return extractZipWithLimits(archivePath,destDir,archiveNames,extractNames,- variant,defaultArchiveResourceLimits,)}@@ -963,7 +902,6 @@ func extractZip(func extractZipWithLimits(archivePath, destDir string,archiveNames, extractNames []string,- variant string,limits archiveResourceLimits,) ([]string, error) {if err := validateArchiveResourceLimits(limits); err != nil {@@ -1010,13 +948,11 @@ func extractZipWithLimits(names = append(names, name)declaredSizes[name] = declaredSize}- uiPack, err := validateArchiveMemberNames(- names, archiveNames, variant, true,- )+ err := validateArchiveMemberNames(names, archiveNames, true)if err != nil {return nil, err}- runtimeNames := runtimeArchiveNames(extractNames, uiPack)+ runtimeNames := append([]string(nil), extractNames...)targetNames := make(map[string]struct{}, len(runtimeNames))for _, name := range runtimeNames {targetNames[name] = struct{}{}@@ -1103,7 +1039,7 @@ func validateWindowsZipMember(raw string) (string, error) {func verifyCandidate(path string) error {ctx, cancel := context.WithTimeout(context.Background(), candidateTimeout)defer cancel()- cmd := exec.CommandContext(ctx, path, "--verify-runtime-assets")+ cmd := exec.CommandContext(ctx, path, "--version")cmd.Stdin = nilcmd.Stdout = io.Discardcmd.Stderr = io.Discard@@ -1163,58 +1099,17 @@ func regularRuntimeFile(path string) bool {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 {+func runtimeSetNames(directory, binaryName string) ([]string, bool) {+ if !regularRuntimeFile(filepath.Join(directory, binaryName)) {return nil, false}- names := []string{integrationsFileName}- if variant == "ui" {- names = append(names, validPacks[0])- }- names = append(names, binaryName)- return names, true+ return []string{binaryName}, true}func runtimeSetReady(- directory, binaryName, variant string, verifier func(string) error,+ directory, binaryName string, verifier func(string) error,) bool {- if _, ok := runtimeSetNames(directory, binaryName, variant); !ok {+ if _, ok := runtimeSetNames(directory, binaryName); !ok {return false}return verifier == nil || verifier(filepath.Join(directory, binaryName)) == nil@@ -1232,7 +1127,7 @@ func requireSafeRuntimeDirectory(directory string) error {}func runtimeSetReadyLocked(- directory, binaryName, variant string, verifier func(string) error,+ directory, binaryName string, verifier func(string) error,) (ready bool, result error) {if err := os.MkdirAll(directory, 0755); err != nil {return false, err@@ -1251,11 +1146,11 @@ func runtimeSetReadyLocked(return false, err}if err := reconcileRuntimeBackups(- directory, binaryName, variant, verifier, lock,+ directory, binaryName, verifier, lock,); err != nil {return false, err}- return runtimeSetReady(directory, binaryName, variant, verifier), nil+ return runtimeSetReady(directory, binaryName, verifier), nil}func copyRuntimeStage(@@ -1338,8 +1233,7 @@ func runtimeBackupDirectoryName(name string) bool {}func runtimeBackupTargetName(name, binaryName string) bool {- return name == binaryName || name == integrationsFileName ||- (strings.HasPrefix(name, "cbm-ui-") && strings.HasSuffix(name, ".pack"))+ return name == binaryName}func createRuntimeBackupDirectory(directory string) (string, error) {@@ -1567,7 +1461,7 @@ func copyRuntimeBackupFile(}func reconcileRuntimeBackups(- directory, binaryName, variant string,+ directory, binaryName string,verifier func(string) error,lock *runtimeSetLock,) error {@@ -1592,7 +1486,7 @@ func reconcileRuntimeBackups(if len(backups) == 0 {return nil}- if runtimeSetReady(directory, binaryName, variant, verifier) {+ if runtimeSetReady(directory, binaryName, verifier) {for _, backup := range backups {if err := cleanupRuntimeBackup(backup, lock); err != nil {return err@@ -2051,11 +1945,11 @@ func attachRuntimeLockReleaseError(result *error, releaseErr error) {}func publishRuntimeSetWithRecoveryAndRenamer(- sourceDirectory, destinationDirectory, binaryName, variant string,+ sourceDirectory, destinationDirectory, binaryName string,verifier func(string) error,renameFile func(string, string) error,) (result error) {- sourceNames, ok := runtimeSetNames(sourceDirectory, binaryName, variant)+ sourceNames, ok := runtimeSetNames(sourceDirectory, binaryName)if !ok {return fmt.Errorf("source release does not contain a complete runtime set")}@@ -2081,13 +1975,13 @@ func publishRuntimeSetWithRecoveryAndRenamer(return err}if err := reconcileRuntimeBackups(- destinationDirectory, binaryName, variant, verifier, lock,+ destinationDirectory, binaryName, verifier, lock,); err != nil {return err}// 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) {+ if runtimeSetReady(destinationDirectory, binaryName, verifier) {return nil}@@ -2121,17 +2015,7 @@ func publishRuntimeSetWithRecoveryAndRenamer(return err}- 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)- }- }+ retireNames := []string{binaryName}retired := make(map[string]struct{}, len(retireNames))// Retire the executable first so a partial publication is never ready.for _, name := range retireNames {@@ -2190,7 +2074,7 @@ func publishRuntimeSetWithRecoveryAndRenamer(}delete(staged, name)}- if !runtimeSetReady(destinationDirectory, binaryName, variant, verifier) {+ if !runtimeSetReady(destinationDirectory, binaryName, verifier) {return fmt.Errorf("published package-cache runtime set failed verification")}if err := assertRuntimeSetLockOwner(lock); err != nil {@@ -2217,11 +2101,11 @@ func publishRuntimeSetWithRecoveryAndRenamer(return nil}preserveWinner := runtimeSetReady(- destinationDirectory, binaryName, variant, verifier,+ destinationDirectory, binaryName, verifier,)if backupDirectory != "" {if recoveryErr := reconcileRuntimeBackups(- destinationDirectory, binaryName, variant, verifier, lock,+ destinationDirectory, binaryName, verifier, lock,); recoveryErr != nil {return fmt.Errorf("%v; package-cache recovery failed: %w", operationErr, recoveryErr,@@ -2235,14 +2119,13 @@ func publishRuntimeSetWithRecoveryAndRenamer(}func publishRuntimeSetWithRecovery(- sourceDirectory, destinationDirectory, binaryName, variant string,+ sourceDirectory, destinationDirectory, binaryName string,verifier func(string) error,) error {return publishRuntimeSetWithRecoveryAndRenamer(sourceDirectory,destinationDirectory,binaryName,- variant,verifier,os.Rename,)@@ -2260,13 +2143,13 @@ func execBinary(executable string, args []string) error {}func createMutationRuntimeSnapshot(- executable, variant string,+ executable 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)+ names, ok := runtimeSetNames(sourceDirectory, binaryName)if !ok {return "", "", fmt.Errorf("cached runtime assets changed before mutation snapshot",@@ -2323,7 +2206,7 @@ func createMutationRuntimeSnapshot(snapshotExecutable = filepath.Join(snapshotDirectory, binaryName)if !runtimeSetReady(- snapshotDirectory, binaryName, variant, verifier,+ snapshotDirectory, binaryName, verifier,) {return "", "", fmt.Errorf("private mutation runtime snapshot failed verification",@@ -2344,7 +2227,6 @@ func runMutationBinary(executable string, args []string) error {func execBinaryWithRuntimeLockAndRunner(executable string,args []string,- variant string,verifier func(string) error,runner func(string, []string) error,) (result error) {@@ -2376,13 +2258,12 @@ func execBinaryWithRuntimeLockAndRunner(return err}if !runtimeSetReady(- directory, filepath.Base(executable), variant, verifier,+ directory, filepath.Base(executable), verifier,) {return fmt.Errorf("cached runtime assets changed before mutation launch")}snapshotDirectory, snapshotExecutable, err := createMutationRuntimeSnapshot(executable,- variant,verifier,func() error { return refreshRuntimeSetLock(lock) },)@@ -2414,7 +2295,6 @@ func execBinaryWithRuntimeLock(executable string, args []string) error {return execBinaryWithRuntimeLockAndRunner(executable,args,- runtimeVariant(),verifyCandidate,runMutationBinary,)diff --git a/pkg/pypi/src/codebase_memory_mcp/_cli.py b/pkg/pypi/src/codebase_memory_mcp/_cli.pyindex cf1538792..2750248a5 100644--- a/pkg/pypi/src/codebase_memory_mcp/_cli.py+++ b/pkg/pypi/src/codebase_memory_mcp/_cli.py@@ -21,18 +21,14 @@ 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",@@ -142,7 +138,7 @@ def _verify_candidate(path: Path) -> None:"""Require a staged native candidate to execute successfully."""try:subprocess.run(- [str(path), "--verify-runtime-assets"],+ [str(path), "--version"],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,@@ -173,13 +169,12 @@ def _files_equal_sha256(left: Path, right: Path) -> bool:return False-def _validate_archive_names(names, archive_names, ui: bool, casefold: bool = False):- """Require the exact release root namespace and return its UI pack name."""+def _validate_archive_names(names, archive_names, casefold: bool = False):+ """Require the exact release root namespace."""required = tuple(archive_names)required_set = set(required)found = set()seen = set()- ui_pack = Nonefor name in names:key = name.casefold() if casefold else nameif key in seen:@@ -188,28 +183,17 @@ def _validate_archive_names(names, archive_names, ui: bool, casefold: bool = Falf"(duplicate or case conflict: {name!r})")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:+ if name not in required_set: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):+ found.add(name)+ if found != required_set or len(seen) != len(required):sys.exit(f"codebase-memory-mcp: archive must contain exactly one of each "f"required root file: {', '.join(required)}")- return ui_packdef _safe_extract_tar(@@ -223,12 +207,8 @@ def _safe_extract_tar(f"codebase-memory-mcp: refusing unsafe tar entry "f"(not a regular root file: {member.name!r})")- ui_pack = _validate_archive_names(- [member.name for member in members], archive_names, ui- )+ _validate_archive_names([member.name for member in members], archive_names)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:@@ -281,13 +261,11 @@ def _safe_extract_zip(f"codebase-memory-mcp: refusing unsafe zip entry "f"(escapes dest: {raw_name!r})")- ui_pack = _validate_archive_names(names, archive_names, ui, casefold=True)+ _validate_archive_names(names, archive_names, casefold=True)# Extract only the validated runtime files. This avoids relying on# platform-specific zip path rewriting and always creates regular files.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:@@ -393,22 +371,18 @@ def _cache_dir() -> Path:return base / "codebase-memory-mcp"-def _variant() -> str:- return "ui" if os.environ.get("CBM_VARIANT", "").lower() == "ui" else "standard"-+def _runtime_dir(version: str) -> Path:+ return _cache_dir() / version-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:+def _bin_path(version: str) -> Path:# One binary per platform: the cached file is the executed file.name = (_WINDOWS_BINARY_NAMEif sys.platform == "win32"else "codebase-memory-mcp")- return _runtime_dir(version, variant) / name+ return _runtime_dir(version) / namedef _execution_path(binary: Path, target_platform: str) -> Path:@@ -428,54 +402,15 @@ def _regular_file(path: Path) -> bool: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- ):+def _runtime_set_names(directory: Path, binary_name: str):+ if not _regular_file(directory / binary_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,- )+ return (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:+ binary = _bin_path(version)+ if _runtime_set_names(binary.parent, binary.name) is None:return Falseif verifier is not None:try:@@ -499,16 +434,16 @@ def _runtime_set_ready_locked(version: str) -> bool:try:_refresh_runtime_lock(lock)_reconcile_runtime_backups(- binary.parent, binary.name, _variant(), _verify_candidate, lock+ binary.parent, binary.name, _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):+def _runtime_set_fingerprint(directory: Path, binary_name: str):"""Identify one complete set so a lock waiter can preserve its winner."""- names = _runtime_set_names(directory, binary_name, variant)+ names = _runtime_set_names(directory, binary_name)if names is None:return Nonetry:@@ -519,33 +454,12 @@ def _runtime_set_fingerprint(directory: Path, binary_name: str, variant: str):return None-def _staged_runtime_names(staged_paths, binary_name: str, variant: str):+def _staged_runtime_names(staged_paths, binary_name: 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- ):+ required = {binary_name}+ if names != required or not _regular_file(staged_paths[binary_name]):raise RuntimeError("staged package cache is incomplete")- return runtime_names+ return (binary_name,)def _windows_process_api():@@ -890,11 +804,7 @@ def _release_runtime_lock(lock):# 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"))- )+ return name == binary_namedef _create_runtime_backup_directory(directory: Path) -> Path:@@ -994,10 +904,8 @@ def _current_runtime_targets(directory: Path, binary_name: str):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:+def _runtime_set_ready_at(directory: Path, binary_name: str, verifier=None) -> bool:+ if _runtime_set_names(directory, binary_name) is None:return Falseif verifier is not None:try:@@ -1068,9 +976,7 @@ def _copy_runtime_backup_file(pass-def _reconcile_runtime_backups(- directory: Path, binary_name: str, variant: str, verifier, lock-):+def _reconcile_runtime_backups(directory: Path, binary_name: 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"]]:@@ -1079,7 +985,7 @@ def _reconcile_runtime_backups(if not backups:return- if _runtime_set_ready_at(directory, binary_name, variant, verifier):+ if _runtime_set_ready_at(directory, binary_name, verifier):for backup in backups:_cleanup_runtime_backup(backup, lock)return@@ -1151,31 +1057,24 @@ 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)+ runtime_names = _staged_runtime_names(staged_paths, binary_name)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- )+ initial_fingerprint = _runtime_set_fingerprint(dest.parent, binary_name)lock, contended = _acquire_runtime_lock(dest.parent)operation_error = Nonetry:_refresh_runtime_lock(lock)- _reconcile_runtime_backups(- dest.parent, binary_name, variant, verifier, lock- )+ _reconcile_runtime_backups(dest.parent, binary_name, 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- )+ locked_fingerprint = _runtime_set_fingerprint(dest.parent, binary_name)if (locked_fingerprint is not Noneand (contended or locked_fingerprint != initial_fingerprint)@@ -1185,13 +1084,7 @@ def _publish_runtime_set(backup_directory = Nonetry: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)+ retire_names = (binary_name,)retired = set()# Retire the executable first: until the final rename, readiness is false.for name in retire_names:@@ -1227,7 +1120,7 @@ def _publish_runtime_set(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:+ if _runtime_set_names(dest.parent, binary_name) is None:raise RuntimeError("published package cache is incomplete")if verifier is not None:verifier(dest.parent / binary_name)@@ -1235,14 +1128,10 @@ def _publish_runtime_set(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- )+ preserve_winner = _runtime_set_ready_at(dest.parent, binary_name, verifier)if backup_directory is not None:try:- _reconcile_runtime_backups(- dest.parent, binary_name, variant, verifier, lock- )+ _reconcile_runtime_backups(dest.parent, binary_name, verifier, lock)except Exception as recovery_error:raise RuntimeError(f"{publication_error}; package-cache recovery failed: "@@ -1271,19 +1160,15 @@ 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.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}"+ archive = f"codebase-memory-mcp-{os_name}-{arch}{portable}.{ext}"url = f"https://github.com/{REPO}/releases/download/v{version}/{archive}"_validate_url_scheme(url)- dest = _bin_path(version, selected_variant)+ dest = _bin_path(version)dest.parent.mkdir(parents=True, exist_ok=True)print(@@ -1307,7 +1192,7 @@ def _download(version: str) -> Path:bin_name = (_WINDOWS_BINARY_NAME if os_name == "windows" else "codebase-memory-mcp")- extraction_names = (bin_name, _INTEGRATIONS_NAME)+ extraction_names = (bin_name,)archive_names = (_WINDOWS_ARCHIVE_NAMESif os_name == "windows"@@ -1321,7 +1206,6 @@ def _download(version: str) -> Path:tmp,archive_names,extraction_names,- selected_variant == "ui",)else:import zipfile@@ -1331,7 +1215,6 @@ def _download(version: str) -> Path:tmp,archive_names,extraction_names,- selected_variant == "ui",)extracted_paths = {}@@ -1348,7 +1231,7 @@ def _download(version: str) -> Path: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:+ if _runtime_set_names(Path(tmp), bin_name) is None:sys.exit("codebase-memory-mcp: extracted runtime set failed content ""verification"@@ -1387,7 +1270,6 @@ def _download(version: str) -> Path:staged_paths,dest,bin_name,- selected_variant,verifier=_verify_candidate,)_verify_candidate(dest)diff --git a/scripts/ci/append-vt-notes.sh b/scripts/ci/append-vt-notes.shindex 189748511..0e5e1342f 100755--- a/scripts/ci/append-vt-notes.sh+++ b/scripts/ci/append-vt-notes.sh@@ -131,6 +131,7 @@ executable_paths = {for association in associations:scan_path = association["scan_path"]association_counts[scan_path] = association_counts.get(scan_path, 0) + 1+tolerated_paths: List[str] = []for result in results:scan_path = result["scan_path"]if scan_path in results_by_path:@@ -145,8 +146,18 @@ for result in results:):if not result[numeric].isdigit():fail(f"malformed numeric result field {numeric}: {scan_path}")- if int(result["malicious"]) != 0 or int(result["suspicious"]) != 0:+ # Mirrors the gate's release policy: a single Microsoft machine-learning+ # verdict is tolerated and disclosed in the notes; anything else must never+ # have reached publication.+ tolerated = (+ int(result["malicious"]) == 1+ and int(result["suspicious"]) == 0+ and result["microsoft_category"] == "malicious"+ )+ if (int(result["malicious"]) != 0 or int(result["suspicious"]) != 0) and not tolerated:fail(f"detected object reached release-note publication: {scan_path}")+ if tolerated:+ tolerated_paths.append(scan_path)if (re.fullmatch(r"[0-9a-f]{64}", result["sha256"]) is Noneor result["virustotal_url"]@@ -156,8 +167,8 @@ for result in results: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 result["microsoft_category"] not in {"undetected", "harmless", "malicious"}:+ fail(f"executable result lacks a decisive 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@@ -172,15 +183,14 @@ for association in associations:fail(f"result hash/size differs from association: {association['scan_path']}")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(member_rows) + len(asset_rows) != len(associations):+if len(member_rows) != len(associations):fail("association manifest contains a non-extracted scan target")archive_hashes: Dict[str, str] = {}for association in associations:archive = association["archive"]archive_sha256 = association["archive_sha256"]if not archive or re.fullmatch(r"[0-9a-f]{64}", archive_sha256) is None:- fail("member/asset association lacks valid archive SHA provenance")+ fail("member association lacks valid archive SHA provenance")previous_sha256 = archive_hashes.get(archive)if previous_sha256 is not None and previous_sha256 != archive_sha256:fail(f"conflicting archive SHA provenance: {archive}")@@ -202,9 +212,7 @@ section = ["",(f"VirusTotal completed **{len(results)} distinct extracted byte objects** covering "- f"**{len(associations)} exact extracted-file associations**: "- f"{len(member_rows)} archive members and "- f"{len(asset_rows)} independently extracted UI-pack assets."+ f"**{len(associations)} exact extracted archive members**."),(f"The extraction manifest binds those associations to "@@ -216,10 +224,26 @@ section = [(f"Every scanned object returned **0 malicious and 0 suspicious** verdicts with "f"{engine_range} decisive engine results (required minimum: {policy})."+ if not tolerated_paths+ else (+ f"{len(results) - len(tolerated_paths)} of {len(results)} scanned objects returned "+ f"**0 malicious and 0 suspicious** verdicts with {engine_range} decisive engine "+ f"results (required minimum: {policy})."+ )),(f"Microsoft returned a decisive clean verdict for all "f"{len(executable_paths)} executable objects."+ if not tolerated_paths+ else (+ f"**{len(tolerated_paths)} object(s) carry a single Microsoft machine-learning "+ f"detection** (`!ml`), which this project treats as a known false positive and "+ f"publishes rather than hides. Every other engine returned clean. See "+ f"[Antivirus False Positives](https://github.com/{repository}"+ f"/blob/main/SECURITY.md#antivirus-false-positives) for the evidence and for how to "+ f"verify these artifacts yourself: "+ + ", ".join(f"`{path}`" for path in sorted(tolerated_paths))+ )),"",(diff --git a/scripts/ci/check-virustotal.sh b/scripts/ci/check-virustotal.shindex d186df13e..393c18cf8 100755--- a/scripts/ci/check-virustotal.sh+++ b/scripts/ci/check-virustotal.sh@@ -217,7 +217,7 @@ def load_expected(path: pathlib.Path) -> Tuple[List[ExpectedObject], int]:size = int(row["size"])association_count = int(row["association_count"])kinds = row["association_kinds"].split(",")- allowed_kinds = {"binary", "pack", "runtime", "ui_asset"}+ allowed_kinds = {"binary", "runtime"}if (association_count < 1or any(not kind or kind not in allowed_kinds for kind in kinds)@@ -288,14 +288,11 @@ def validate_associations(if key in seen:raise GateError(f"duplicate release association: {key}")seen.add(key)- if association_type not in {"member", "pack_asset"} or not row["archive"]:+ if association_type != "member" 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 provenance: {key}")- if 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"+ semantic_valid = bool(row["member"]) and not row["asset_path"]if not semantic_valid:raise GateError(f"malformed release association semantics: {key}")expected = expected_by_path.get(row["scan_path"])@@ -460,7 +457,7 @@ def parse_completed(document: object, submission: Submission) -> Tuple[str, Optimalicious = normalized["malicious"]suspicious = normalized["suspicious"]- detections: List[str] = []+ detections: List[Tuple[str, str, str, str, str]] = []results = attributes.get("results")microsoft_category = ""microsoft_engine_version = ""@@ -480,9 +477,7 @@ def parse_completed(document: object, submission: Submission) -> Tuple[str, Optilabel = 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})"- )+ detections.append((one_line(engine), label, str(category), version, updated))if engine == "Microsoft":microsoft_category = str(category)microsoft_engine_version = required_one_line_string(@@ -611,6 +606,26 @@ def write_results(temporary.unlink()+# Release policy: exactly ONE Microsoft machine-learning verdict is tolerated.+#+# Microsoft's `!ml` suffix marks a heuristic/ML classification rather than a+# signature match, and it is an endemic false positive on large unsigned native+# binaries -- llama.cpp, GitHub's own `gh`, Microsoft's own Go toolchain and+# Anthropic's Claude installer have all carried the same family. Our own+# evidence is that the verdict is not a property of our bytes: it inverts across+# architectures and link modes, moves between sibling artifacts of one build,+# and lands in different variant buckets for the same source.+#+# Everything else still fails the release: two or more engines, any label that+# is not `!ml` (a signature hit is a real finding), any non-Microsoft engine,+# any suspicious verdict, and every infrastructure error.+def is_tolerated_detection(result, detections) -> bool:+ if result.suspicious or result.malicious != 1 or len(detections) != 1:+ return False+ engine, label, category, _version, _updated = detections[0]+ return engine == "Microsoft" and category == "malicious" and label.endswith("!ml")++def main() -> None:api_key = required_env("VT_API_KEY")raw_analysis = required_env("VT_ANALYSIS")@@ -674,6 +689,7 @@ def main() -> None:print(f" {submission.expected.scan_path}: {status}; will retry round-robin")continuecompleted.append(result)+ tolerated = is_tolerated_detection(result, detections)if result.completed_engines < min_engines:message = (f"{submission.expected.scan_path} completed with only "@@ -688,11 +704,14 @@ def main() -> None:f"({result.malicious} malicious, {result.suspicious} suspicious / "f"{result.completed_engines} decisive engines)")- failures.append(message)- print(f"BLOCKED: {message}")+ if tolerated:+ print(f"TOLERATED: {message}")+ else:+ failures.append(message)+ print(f"BLOCKED: {message}")if detections:- for detection in detections:- print(f" detected by: {detection}")+ for engine, label, _category, version, updated in detections:+ print(f" detected by: {engine} = {label} (engine {version}, defs {updated})")else:print(" detected by: <engine names unavailable in the analysis response>")print(diff --git a/scripts/ci/extract-release-archives.sh b/scripts/ci/extract-release-archives.shindex 48e7aaf75..b77a1f166 100755--- a/scripts/ci/extract-release-archives.sh+++ b/scripts/ci/extract-release-archives.sh@@ -4,23 +4,22 @@## Usage:# extract-release-archives.sh <archive-dir> <output-dir> \-# [--archive-scope=all|ui] [--expect-archives=N] [--expect-binaries=N] [--expect-packs=N] \+# [--expect-archives=N] [--expect-binaries=N] \# [--expect-runtime-files=N]## The output directory is published as one atomic bundle:# objects/ one file per distinct byte sequence-# associations.tsv every extracted member and CBMUIPK asset -> scan object+# associations.tsv every extracted archive member -> scan object# scan-set.tsv the exact path/hash/size set the VT action must return## Every archive is validated and hashed for provenance, but downloadable-# .tar.gz/.zip release containers are not scanned. Their exact members and the-# uncompressed HTML/JavaScript/CSS/etc payloads inside every CBMUIPK v1 pack are-# covered. Identical bytes are uploaded once, but no extracted member/asset+# .tar.gz/.zip release containers are not scanned. Their exact members are+# covered instead. Identical bytes are uploaded once, but no extracted member# association is discarded.set -euo pipefailif [ "$#" -lt 2 ]; then- echo "Usage: $0 <archive-dir> <output-dir> [--archive-scope=all|ui] [--expect-archives=N] [--expect-binaries=N] [--expect-packs=N] [--expect-runtime-files=N]" >&2+ echo "Usage: $0 <archive-dir> <output-dir> [--expect-archives=N] [--expect-binaries=N] [--expect-runtime-files=N]" >&2exit 2fi@@ -72,28 +71,15 @@ UNIX_TARGETS = ("linux-arm64-portable",)WINDOWS_TARGETS = ("windows-amd64", "windows-arm64")-UI_ARCHIVES = frozenset(- [- f"codebase-memory-mcp-ui-{target}.tar.gz"- for target in UNIX_TARGETS- ]- + [- f"codebase-memory-mcp-ui-{target}.zip"- for target in WINDOWS_TARGETS- ]-)-STANDARD_ARCHIVES = frozenset(+CANONICAL_ARCHIVES = frozenset([f"codebase-memory-mcp-{target}.tar.gz" for target in UNIX_TARGETS]+ [f"codebase-memory-mcp-{target}.zip" for target in WINDOWS_TARGETS])-CANONICAL_ARCHIVES = UI_ARCHIVES | STANDARD_ARCHIVES-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 = {@@ -295,22 +281,13 @@ class ObjectStore:def parse_arguments(argv: Sequence[str],-) -> Tuple[pathlib.Path, pathlib.Path, Dict[str, Optional[int]], 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()- archive_scope = "all"for argument in argv[3:]:option, separator, raw_value = argument.partition("=")- if separator and option == "--archive-scope":- if "archive_scope" in seen:- raise ContractError(f"duplicate option: {option}")- if raw_value not in {"all", "ui"}:- raise ContractError("--archive-scope must be all or ui")- archive_scope = raw_value- seen.add("archive_scope")- continueif not separator or option not in COUNT_OPTIONS:raise ContractError(f"unknown option: {argument}")key = COUNT_OPTIONS[option]@@ -320,164 +297,33 @@ def parse_arguments(raise ContractError(f"{option} requires a non-negative integer")expected[key] = int(raw_value)seen.add(key)- return archive_dir, output_dir, expected, archive_scope+ return archive_dir, output_dir, expected-def validate_namespace(archive_name: str, names: Iterable[str]) -> Tuple[str, Dict[str, str]]:+def validate_namespace(archive_name: str, names: Iterable[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, kindsif extras:raise ContractError(f"unexpected archive member in {archive_name}: {sorted(extras)[0]}")- if len(name_set) != 5 or name_set != set(fixed):+ if 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}"+ f"member namespace mismatch in {archive_name}: expected exactly 4 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+ return fixeddef add_association(@@ -545,12 +391,6 @@ def process_member(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,@@ -561,27 +401,6 @@ def process_member(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(@@ -605,7 +424,7 @@ def process_tar(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])+ 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:@@ -622,7 +441,7 @@ def process_tar(archive_sha256=archive_sha256,variant=variant,)- return variant, kinds, total+ return kinds, totaldef process_zip(@@ -651,7 +470,7 @@ def process_zip(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])+ 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(@@ -665,7 +484,7 @@ def process_zip(archive_sha256=archive_sha256,variant=variant,)- return variant, kinds, total+ return kinds, totaldef write_tsv(@@ -688,7 +507,7 @@ def write_tsv(def main(argv: Sequence[str]) -> None:- archive_dir, output_dir, expected, archive_scope = parse_arguments(argv)+ 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 ("", ".", ".."):@@ -701,13 +520,13 @@ def main(argv: Sequence[str]) -> None:archive_paths = sorted(archive_dir.iterdir(), key=lambda candidate: candidate.name)actual_names = {path.name for path in archive_paths}- expected_names = UI_ARCHIVES if archive_scope == "ui" else CANONICAL_ARCHIVES+ expected_names = CANONICAL_ARCHIVESif actual_names != expected_names or len(archive_paths) != len(expected_names):missing = sorted(expected_names - actual_names)unexpected = sorted(actual_names - expected_names)raise ContractError(f"archive namespace mismatch: expected exact canonical {len(expected_names)} "- f"({archive_scope}); missing={missing}, unexpected={unexpected}"+ f"missing={missing}, unexpected={unexpected}")for path in archive_paths:mode = path.lstat().st_mode@@ -723,9 +542,7 @@ def main(argv: Sequence[str]) -> None:counts = {"archives": 0,"binaries": 0,- "packs": 0,"runtime_files": 0,- "pack_assets": 0,"associations": 0,"scan_objects": 0,}@@ -738,14 +555,16 @@ def main(argv: Sequence[str]) -> None:archive_store = ObjectStore(pathlib.Path(temporary) / "archives")for archive_path in archive_paths:archive_name = archive_path.name- variant = "ui" if archive_name.startswith("codebase-memory-mcp-ui-") else "standard"+ # One composition ships; the column is retained so the association+ # schema stays stable for the release-notes and gate consumers.+ variant = "release"archive_object = archive_store.ingest_path(archive_path,ceiling=MAX_ARCHIVE_BYTES,label=archive_name,)archive_sha256 = archive_object.sha256- _, kinds, member_total = (+ kinds, member_total = (process_tar(archive_object.path,archive_name=archive_name,@@ -769,13 +588,11 @@ def main(argv: Sequence[str]) -> None:raise ContractError("release matrix exceeds total uncompressed byte ceiling")counts["archives"] += 1counts["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"):+ for key in ("archives", "binaries", "runtime_files"):wanted = expected[key]if wanted is not None and counts[key] != wanted:display = key.replace("_files", " files")@@ -786,7 +603,6 @@ def main(argv: Sequence[str]) -> None:rows.sort(key=lambda row: (str(row["archive"]),- {"member": 0, "pack_asset": 1}[str(row["association_type"])],str(row["member"]),str(row["asset_path"]),)@@ -794,9 +610,7 @@ def main(argv: Sequence[str]) -> None:metadata_order = ("archives","binaries",- "packs","runtime_files",- "pack_assets","associations","scan_objects",)@@ -837,8 +651,7 @@ def main(argv: Sequence[str]) -> None: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"+ f"{counts['binaries']} binaries and {counts['runtime_files']} runtime files")print(f"scan bundle: {counts['scan_objects']} distinct byte objects cover "diff --git a/scripts/ci/smoke-artifact.sh b/scripts/ci/smoke-artifact.shindex 539a70415..be3f487f9 100755--- a/scripts/ci/smoke-artifact.sh+++ b/scripts/ci/smoke-artifact.sh@@ -17,8 +17,7 @@ cd "$ROOT"usage() {cat <<'EOF'-Usage: scripts/ci/smoke-artifact.sh <goos> <goarch> [--variant standard|ui]- [VAR=VAL ...]+Usage: scripts/ci/smoke-artifact.sh <goos> <goarch> [VAR=VAL ...]Build → package (scripts/package-release.sh) → extract → smoke the EXTRACTEDartifact through the canonical wrapper, exactly like the release venue:@@ -26,9 +25,6 @@ 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- assets become mandatory — a standard binary cannot pass a ui run).-Make passthrough (VAR=VAL): CC= CXX= STATIC=1 ... forwarded to build steps.Environment: BUILD_DIR (default build/c) — build tree used for the archive.On failure the work directory is preserved for post-mortem (path printed).@@ -37,17 +33,11 @@ EOFGOOS=""GOARCH=""-VARIANT="standard"BUILD_ARGS=()expect_value=""for arg in "$@"; do- if [ "$expect_value" = "variant" ]; then- VARIANT="$arg"; expect_value=""; continue- ficase "$arg" in-h | --help) usage; exit 0 ;;- --variant) expect_value="variant" ;;- --variant=*) VARIANT="${arg#--variant=}" ;;-*)echo "smoke-artifact: unknown option '$arg'. Please consult --help." >&2exit 2@@ -64,11 +54,7 @@ for arg in "$@"; doesacdone[ -n "$GOOS" ] && [ -n "$GOARCH" ] || { usage >&2; exit 2; }-case "$VARIANT" in-standard) SUFFIX=""; UI_FLAG=() ;;-ui) SUFFIX="-ui"; UI_FLAG=(--with-ui) ;;-*) echo "smoke-artifact: variant must be 'standard' or 'ui'. Please consult --help." >&2; exit 2 ;;-esac+UI_FLAG=(--with-ui)case "$GOARCH" in*-portable) BUILD_ARGS+=("STATIC=1") ;;esac@@ -95,10 +81,10 @@ cleanup() {}trap cleanup EXIT-scripts/package-release.sh "$GOOS" "$GOARCH" --variant "$VARIANT" \+scripts/package-release.sh "$GOOS" "$GOARCH" \--out-dir "$WORK_DIR" ${BUILD_ARGS[@]+"${BUILD_ARGS[@]}"}-NAME="codebase-memory-mcp${SUFFIX}-${GOOS}-${GOARCH}"+NAME="codebase-memory-mcp-${GOOS}-${GOARCH}"EXTRACT_DIR="$WORK_DIR/extract"mkdir -p "$EXTRACT_DIR"if [ "$GOOS" = "windows" ]; then@@ -108,7 +94,7 @@ if [ "$GOOS" = "windows" ]; then# stub came back.test ! -e "$EXTRACT_DIR/codebase-memory-mcp.payload.exe"echo "=== smoke-artifact: smoking EXTRACTED $NAME.zip via vm-smoke.sh ==="- SMOKE_ARCH="$GOARCH" SMOKE_VARIANT="$VARIANT" \+ SMOKE_ARCH="$GOARCH" \CBM_SMOKE_ARTIFACT_DIR="$EXTRACT_DIR" \bash test-infrastructure/vm/vm-smoke.shelse@@ -116,6 +102,6 @@ elsechmod +x "$EXTRACT_DIR/codebase-memory-mcp"echo "=== smoke-artifact: smoking EXTRACTED $NAME.tar.gz via smoke-local.sh ==="CBM_SMOKE_ARTIFACT_DIR="$EXTRACT_DIR" \- scripts/smoke-local.sh "$EXTRACT_DIR/codebase-memory-mcp" "$VARIANT"+ scripts/smoke-local.sh "$EXTRACT_DIR/codebase-memory-mcp"fiecho "=== smoke-artifact: $NAME passed ==="diff --git a/scripts/smoke-local.sh b/scripts/smoke-local.shindex 9aa8c6305..5068a1caf 100755--- a/scripts/smoke-local.sh+++ b/scripts/smoke-local.sh@@ -48,7 +48,6 @@ if [ $# -gt 2 ]; thenfiBINARY="${1:?smoke-local: missing <binary> argument. Please consult --help.}"-VARIANT="${2:-standard}"ROOT="$(cd "$(dirname "$0")/.." && pwd)"BINARY="$(cd "$(dirname "$BINARY")" && pwd)/$(basename "$BINARY")"@@ -56,15 +55,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-# supplying a standard binary can no longer pass quietly.-case "$VARIANT" in-standard) SUFFIX="" ; REQUIRE_UI=0 ;;-ui) SUFFIX="-ui" ; REQUIRE_UI=1 ;;-*) echo "smoke-local: variant must be 'standard' or 'ui'. Please consult --help." >&2; exit 2 ;;-esac+# Every shipped binary carries the embedded UI, so Phase 15's documented+# "no embedded assets" SKIP is always a failure here.+REQUIRE_UI=1# Unset (the local + PR default): synthesize the release sidecars from this# checkout. Set: take them from an EXTRACTED release artifact, so the release@@ -133,23 +126,15 @@ fi# Member set and ORDER mirror scripts/package-release.sh (the Windows# single-binary contract locks that order); a fixture with a different inventory# would smoke a release layout we never ship.-EXPECTED_ARTIFACT="codebase-memory-mcp${SUFFIX}-${OS}-${ARCH}.tar.gz"+EXPECTED_ARTIFACT="codebase-memory-mcp-${OS}-${ARCH}.tar.gz"tar -czf "$FIXTURE_DIR/$EXPECTED_ARTIFACT" -C "$FIXTURE_DIR" \codebase-memory-mcp 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# 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"- fi+ "$FIXTURE_DIR/codebase-memory-mcp-${OS}-${ARCH}-portable.tar.gz"fi(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 38b5c47db..2cc59dad3 100755--- a/scripts/smoke-test.sh+++ b/scripts/smoke-test.sh@@ -3273,11 +3273,9 @@ if [ "$DL_OS" = "darwin" ] || [ "$DL_OS" = "linux" ]; thenelseDL_EXT="zip"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}"-# 12a: curl download (try standard, then UI variant)+# 12a: curl downloadecho "--- Phase 12a: curl download ---"# --noproxy '*': never route the local test server through a proxy — a proxy env# var present on some runners (notably windows-11-arm) made curl fail to reach@@ -3285,15 +3283,10 @@ echo "--- Phase 12a: curl download ---"# surface curl's stderr instead of swallowing it so the reason is visible.CURL12_ERR="$DL_DIR/curl12a.err"if ! curl -fSL --noproxy '*' -o "$DL_DIR/$DL_ARCHIVE" "$SMOKE_DOWNLOAD_URL/$DL_ARCHIVE" 2>"$CURL12_ERR"; then- # Try UI variant- if curl -fSL --noproxy '*' -o "$DL_DIR/$DL_ARCHIVE_UI" "$SMOKE_DOWNLOAD_URL/$DL_ARCHIVE_UI" 2>>"$CURL12_ERR"; then- DL_ARCHIVE="$DL_ARCHIVE_UI"- else- echo "FAIL 12a: curl download failed (tried standard and ui variants)"- echo "--- curl stderr (url: $SMOKE_DOWNLOAD_URL/$DL_ARCHIVE) ---"- cat "$CURL12_ERR" 2>/dev/null || true- exit 1- fi+ echo "FAIL 12a: curl download failed"+ echo "--- curl stderr (url: $SMOKE_DOWNLOAD_URL/$DL_ARCHIVE) ---"+ cat "$CURL12_ERR" 2>/dev/null || true+ exit 1fiif [ ! -s "$DL_DIR/$DL_ARCHIVE" ]; thenecho "FAIL 12a: downloaded archive is empty"diff --git a/scripts/test.sh b/scripts/test.shindex f7b813e2b..6d3f11f96 100755--- a/scripts/test.sh+++ b/scripts/test.sh@@ -233,6 +233,12 @@ bash "$ROOT/tests/test_venue_parity_contract.sh"echo "=== Step 0k: spawn console-window contract (#1427) ==="bash "$ROOT/tests/test_spawn_no_window_contract.sh"+echo "=== Step 0l: VirusTotal release-notes + evidence contract ==="+bash "$ROOT/tests/test_vt_release_notes_contract.sh"++echo "=== Step 0m: VirusTotal gate policy contract ==="+bash "$ROOT/tests/test_vt_gate_policy_contract.sh"+# Verify compiler supports target archverify_compiler "$CC"diff --git a/test-infrastructure/vm/vm-smoke.sh b/test-infrastructure/vm/vm-smoke.shindex ebbc62559..c646707ee 100755--- a/test-infrastructure/vm/vm-smoke.sh+++ b/test-infrastructure/vm/vm-smoke.sh@@ -28,7 +28,6 @@ Run inside the VM's CLANGARM64 shell (or a CI msys2 shell) from the repo root.Environment:SMOKE_ARCH arm64 (default) | amd64 — selects the served artifact name.- SMOKE_VARIANT standard (default) | ui. ui requires the embedded UI:Phase 15's "no assets" SKIP becomes a FAILURE, so a standardbinary cannot pass a ui run.CBM_SMOKE_ARTIFACT_DIR@@ -70,20 +69,13 @@ elsefiSMOKE_ARCH="${SMOKE_ARCH:-arm64}"-SMOKE_VARIANT="${SMOKE_VARIANT:-standard}"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-# supplying a standard binary can no longer pass quietly.-case "$SMOKE_VARIANT" in-standard) SUFFIX="" ; REQUIRE_UI=0 ;;-ui) SUFFIX="-ui" ; REQUIRE_UI=1 ;;-*) echo "vm-smoke: SMOKE_VARIANT must be standard or ui. Please consult --help." >&2; exit 2 ;;-esac+# Every shipped binary carries the embedded UI, so Phase 15's documented+# "no embedded assets" SKIP is always a failure here.+REQUIRE_UI=1PROFILE_ROOT="$(cygpath -u "$USERPROFILE")"SMOKE_DIR="$(mktemp -d "$PROFILE_ROOT/cbm-vm-smoke.XXXXXX")"@@ -158,14 +150,11 @@ elsefi# Member set + ORDER mirror scripts/package-release.sh (Windows).-EXPECTED_ARTIFACT="codebase-memory-mcp${SUFFIX}-windows-${SMOKE_ARCH}.zip"+EXPECTED_ARTIFACT="codebase-memory-mcp-windows-${SMOKE_ARCH}.zip"(cd "$FIXTURE_DIR"zip -q "$EXPECTED_ARTIFACT" \codebase-memory-mcp.exe LICENSE install.ps1 THIRD_PARTY_NOTICES.md- if [ -n "$SUFFIX" ]; then- cp "$EXPECTED_ARTIFACT" "codebase-memory-mcp-windows-${SMOKE_ARCH}.zip"- fisha256sum *.zip > checksums.txt)diff --git a/tests/test_release_archive_extractor_contract.sh b/tests/test_release_archive_extractor_contract.shdeleted file mode 100644index b07eb37fe..000000000--- a/tests/test_release_archive_extractor_contract.sh+++ /dev/null@@ -1,592 +0,0 @@-#!/usr/bin/env bash-# Contract for the release scan boundary: archives are validated and hashed;-# only exact extracted members and independently parsed UI-pack assets enter-# the byte-deduplicated, atomically published scan set.-set -euo pipefail--ROOT="$(cd "$(dirname "$0")/.." && pwd)"--python3 - "$ROOT" "$BASH" <<'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])-bash_executable = pathlib.Path(sys.argv[2])-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- ]- )-)-ui_archive_names = tuple(name for name in archive_names if name.startswith("codebase-memory-mcp-ui-"))-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()-]-ui_expected_base_counts = {- "archives": 8,- "binaries": 8,- "packs": 8,- "runtime_files": 32,-}-ui_count_args = [- "--archive-scope=ui",- *[- f"--expect-{key.replace('_', '-')}={value}"- for key, value in ui_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,- selected_names: Tuple[str, ...] = archive_names,-) -> 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 selected_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:- 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(- [- str(bash_executable),- 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 or len(ui_archive_names) != 8:- fail("fixture matrix no longer describes 16 canonical archives / eight UI 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-v3"- )- expected_pack_assets = 8 * len(asset_payloads)- expected_associations = 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 extracted member/asset association")- actual_associations = {- (row["association_type"], row["archive"], row["member"], row["asset_path"]): row- for row in rows- }- if any(row["association_type"] == "archive" or row["kind"] == "archive" for row in rows):- fail("archive containers must not appear in the VirusTotal association set")- if set(actual_associations) != set(expected):- fail("association manifest keys differ from exact shipped associations")- archive_hashes = {- name: hashlib.sha256((valid / "archives" / name).read_bytes()).hexdigest()- for name in archive_names- }- 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}")- if row["archive_sha256"] != archive_hashes[row["archive"]]:- fail(f"association archive provenance 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-v2")- 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']}")-- ui_only = work / "ui-only"- ui_expected = build_matrix(ui_only / "archives", selected_names=ui_archive_names)- ui_output = ui_only / "scan"- ui_result = invoke(ui_only / "archives", ui_output, ui_count_args)- if ui_result.returncode != 0:- fail(f"canonical UI-only matrix was rejected: {ui_result.stdout.strip()}")- ui_metadata, ui_rows = parse_manifest(- ui_output / "associations.tsv", "cbm-release-scan-associations-v3"- )- ui_associations = 48 + expected_pack_assets- if ui_metadata != {- **ui_expected_base_counts,- "pack_assets": expected_pack_assets,- "associations": ui_associations,- "scan_objects": len(set(ui_expected.values())),- }:- fail(f"UI-only association metadata mismatch: {ui_metadata!r}")- if len(ui_rows) != ui_associations or {row["variant"] for row in ui_rows} != {"ui"}:- fail("UI-only scan scope does not cover exactly the eight UI archives")- ui_as_all_output = ui_only / "scan-as-all"- ui_as_all = invoke(ui_only / "archives", ui_as_all_output, count_args)- if (- ui_as_all.returncode == 0- or "expected exact canonical 16 (all)" not in ui_as_all.stdout- or ui_as_all_output.exists()- ):- fail("UI-only archives must require an explicit closed archive scope")-- 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 (all)",- "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 (all)",- "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 archive bytes used for provenance")-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")-build = (root / ".github/workflows/_build.yml").read_text(encoding="utf-8")-smoke = (root / ".github/workflows/_smoke.yml").read_text(encoding="utf-8")-if "ui_only" in build or "Build standard binary" in build:- fail("canonical build workflow must not retain a non-UI release path")-if build.count("--variant ui") != 4:- fail("canonical build workflow must package exactly its four UI-enabled build families")-if "ui_only" in smoke or "VARIANTS='[\"ui\"]'" not in smoke or "standard" in smoke.split("VARIANTS=", 1)[1].split("\n", 1)[0]:- fail("release smoke matrix must expose only the UI-enabled runtime")-if "ui_only" in dry_run or "--archive-scope=ui" not in dry_run:- fail("dry-run must use the canonical UI-only build/smoke/extraction path")-if "--archive-scope=ui" not in release:- fail("release verification must accept only the shipped UI-enabled archives")-if (- "path: ${{ runner.temp }}/release-archives" not in dry_run- or 'extract-release-archives.sh "$RUNNER_TEMP/release-archives" binaries' not in dry_run- or "path: assets" in dry_run- or "extract-release-archives.sh assets binaries" in dry_run-):- fail("dry-run must isolate downloaded archives from tracked checkout assets")-if (- 'ARCHIVE_DIR="$RUNNER_TEMP/release-archives"' not in release- or '--dir "$ARCHIVE_DIR"' not in release- or 'extract-release-archives.sh "$ARCHIVE_DIR" binaries' not in release- or "--dir assets" in release- or "extract-release-archives.sh assets binaries" in release-):- fail("release verification must isolate downloaded archives from tracked checkout assets")-for workflow_name, workflow, arguments in (- ("release", release, ui_count_args),- ("dry-run", dry_run, ui_count_args),-):- for argument in arguments:- 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_smoke_fixture_contract.sh b/tests/test_smoke_fixture_contract.shindex 17f35df07..111b5c7cd 100755--- a/tests/test_smoke_fixture_contract.sh+++ b/tests/test_smoke_fixture_contract.sh@@ -5,23 +5,19 @@ set -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"-python3 - "$ROOT" "$BASH" <<'PY'+python3 - "$ROOT" <<'PY'from __future__ import annotations-import hashlib-import osimport pathlibimport reimport subprocessimport sys-import tarfileimport tempfileimport timeimport urllib.requestroot = pathlib.Path(sys.argv[1])-bash_executable = pathlib.Path(sys.argv[2])failures: list[str] = []@@ -48,32 +44,9 @@ 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(- [- str(bash_executable),- 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.@@ -161,23 +134,18 @@ for relative, source in (f"{relative} must pin isolated {variable}",)-# Unix fixtures mirror the exact release variant surface.+# Unix fixtures mirror the release archive surface and Linux update aliases.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 "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",+ and "codebase-memory-mcp-${OS}-${ARCH}.tar.gz" in smoke_local,+ "smoke-local.sh must create the selected variant and standard alias",)require("codebase-memory-mcp${SUFFIX}-${OS}-${ARCH}-portable.tar.gz" in smoke_local- 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",+ and "codebase-memory-mcp-${OS}-${ARCH}-portable.tar.gz" in smoke_local,+ "smoke-local.sh must create Linux portable selected-variant and standard aliases",)require('CBM_CACHE_DIR="$WORK_DIR/cache"' in smoke_local@@ -195,9 +163,9 @@ require("fixture checksums must name exact artifact basenames, never ./-prefixed paths",)-# 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.+# Native Windows packages and serves the exact four-file release bundle (ONE+# binary, like every other platform), then runs the full smoke from a protected+# profile-rooted directory/cache.for name in ("codebase-memory-mcp.exe","LICENSE",@@ -210,16 +178,6 @@ 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@@ -304,7 +262,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 runtime set's one executable through Wine and through a "+ "docker-compose Windows cross-smoke must execute the single binary through Wine and through a ""Wine Windows parent",)require(@@ -347,93 +305,6 @@ 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(- 'ARCHIVE_DIR="$RUNNER_TEMP/release-archives"' in release_workflow- and 'scripts/ci/extract-release-archives.sh "$ARCHIVE_DIR" binaries' in release_workflow,- "release verification must feed the canonical extractor from an isolated archive directory",-)-require(- "cbm-release-scan-associations-v3" in release_extractor- and "cbm-release-scan-set-v2" 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 and hash every archive, then retain only exact "- "member/UI-asset associations and one scan object per distinct extracted byte sequence",-)require("MSYS2_ARG_CONV_EXCL='*'" in smoke_testand 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File' in smoke_test@@ -652,226 +523,6 @@ 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(- [- str(bash_executable),- 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_vt_gate_zero_tolerance_contract.sh b/tests/test_vt_gate_policy_contract.shsimilarity index 81%rename from tests/test_vt_gate_zero_tolerance_contract.shrename to tests/test_vt_gate_policy_contract.shindex 33f3f11f8..1d291b5d4 100644--- a/tests/test_vt_gate_zero_tolerance_contract.sh+++ b/tests/test_vt_gate_policy_contract.sh@@ -1,7 +1,12 @@#!/usr/bin/env bash-# 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.+# Contract: the VT gate is an exact-set, content-bound, minimum-engine gate.+# Empty, partial, duplicate, unexpected or malformed action output fails before+# a release can be described as scanned.+#+# Detection policy: EXACTLY ONE Microsoft machine-learning (`!ml`) verdict is+# tolerated and disclosed. Two or more engines, any non-`!ml` label, any+# non-Microsoft engine, any suspicious verdict and every infrastructure error+# still block.set -euo pipefailROOT="$(cd "$(dirname "$0")/.." && pwd)"@@ -14,9 +19,12 @@ hash_file() {sha256sum "$1" 2>/dev/null | awk '{print $1}' || shasum -a 256 "$1" | awk '{print $1}'}-for needle in defender-endpoint-verification av-endpoint-verify false-positive false_positive; do+# Tripwire for the REVERTED endpoint-verification mechanism specifically. The+# current `!ml` tolerance is a policy branch inside this gate, not a callout to+# an external verification service, and must never become one.+for needle in defender-endpoint-verification av-endpoint-verify; doif grep -q "$needle" "$GATE"; then- fail "gate references reverted/tolerance machinery '$needle'"+ fail "gate references reverted endpoint-verification machinery '$needle'"fidone@@ -117,6 +125,43 @@ cat > "$FIX/responses/named-engine.json" <<EOF}}}}EOF+cat > "$FIX/responses/ms-signature.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"id":"ms-signature","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:Win32/Emotet",+ "engine_version":"1.26070","engine_update":"20260808"}+ }}}}+EOF++cat > "$FIX/responses/other-engine.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"id":"other-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":"undetected","result":null,+ "engine_version":"1.26070","engine_update":"20260808"},+ "Kaspersky":{"category":"malicious","result":"Trojan.Generic!ml",+ "engine_version":"22","engine_update":"20260808"}+ }}}}+EOF++cat > "$FIX/responses/two-engines.json" <<EOF+{"meta":{"file_info":{"sha256":"$PROBE_SHA","size":$PROBE_SIZE}},+ "data":{"id":"two-engines","type":"analysis","attributes":{"status":"completed",+ "stats":{"malicious":2,"suspicious":0,"undetected":58,"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":"malicious","result":"Trojan.Generic!ml",+ "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",@@ -230,16 +275,28 @@ donefail "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"-[ "$(run_gate "binaries/objects/probe=$(url_for named-engine)")" != "0" ] || \- fail "named-engine detection must block"+# A single Microsoft `!ml` verdict is the tolerated case: it passes, but it is+# reported and recorded rather than silently downgraded to "clean".+[ "$(run_gate "binaries/objects/probe=$(url_for named-engine)")" = "0" ] || \+ fail "a single Microsoft !ml detection must be tolerated: $(cat "$FIX/last.log")"+grep -q 'TOLERATED:' "$FIX/last.log" || \+ fail "a tolerated detection must be reported as TOLERATED, never as OK"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"+ fail "tolerated detection was not preserved as workflow evidence"if grep -q 'detected by: Kaspersky' "$FIX/last.log"; thenfail "gate listed a non-flagging engine as a detection"fi+# Everything adjacent to the tolerated case still blocks.+[ "$(run_gate "binaries/objects/probe=$(url_for ms-signature)")" != "0" ] || \+ fail "a Microsoft signature (non-!ml) detection must block"+[ "$(run_gate "binaries/objects/probe=$(url_for other-engine)")" != "0" ] || \+ fail "a non-Microsoft detection must block"+[ "$(run_gate "binaries/objects/probe=$(url_for two-engines)")" != "0" ] || \+ fail "two flagging engines must 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"diff --git a/tests/test_vt_release_notes_contract.sh b/tests/test_vt_release_notes_contract.shindex 6427ce48b..79c61af31 100644--- a/tests/test_vt_release_notes_contract.sh+++ b/tests/test_vt_release_notes_contract.sh@@ -17,14 +17,12 @@ cat > "$FIX/binaries/associations.tsv" <<EOF# cbm-release-scan-associations-v3# archives=1# binaries=1-# packs=0-# runtime_files=0-# pack_assets=1+# runtime_files=1# associations=2# scan_objects=2association_type archive archive_sha256 variant kind member asset_path mime scan_path object_sha256 size-member codebase-memory-mcp-linux-amd64.tar.gz $ARCHIVE_SHA standard binary codebase-memory-mcp objects/member $MEMBER_SHA 40-pack_asset codebase-memory-mcp-linux-amd64.tar.gz $ARCHIVE_SHA ui ui_asset cbm-ui-$ASSET_SHA.pack /assets/app.js application/javascript objects/script $ASSET_SHA 20+member codebase-memory-mcp-linux-amd64.tar.gz $ARCHIVE_SHA release binary codebase-memory-mcp objects/member $MEMBER_SHA 40+member codebase-memory-mcp-linux-amd64.tar.gz $ARCHIVE_SHA release runtime LICENSE objects/license $ASSET_SHA 20EOFcat > "$FIX/binaries/vt-results.tsv" <<EOF# cbm-virustotal-results-v1@@ -35,7 +33,7 @@ cat > "$FIX/binaries/vt-results.tsv" <<EOF# max_completed_engines=61scan_path sha256 size association_count completed_engines total_engines malicious suspicious analysis_id microsoft_category microsoft_engine_version microsoft_engine_update virustotal_urlobjects/member $MEMBER_SHA 40 1 59 62 0 0 analysis-a undetected 1.26070 20260808 https://www.virustotal.com/gui/file/$MEMBER_SHA/detection-objects/script $ASSET_SHA 20 1 61 64 0 0 analysis-b https://www.virustotal.com/gui/file/$ASSET_SHA/detection+objects/license $ASSET_SHA 20 1 61 64 0 0 analysis-b undetected 1.26070 20260808 https://www.virustotal.com/gui/file/$ASSET_SHA/detectionEOFcat > "$FIX/current.md" <<'EOF'Intro text.@@ -100,7 +98,7 @@ grep -q 'Intro text.' "$FIX/first.md" || fail "content before marked section wasgrep -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 extracted byte objects' "$FIX/first.md" || fail "unique extracted-object scope missing"-grep -q '2 exact extracted-file associations' "$FIX/first.md" || fail "extracted-file association scope missing"+grep -q '2 exact extracted archive members' "$FIX/first.md" || fail "extracted member scope missing"grep -q '1 downloadable archive' "$FIX/first.md" || fail "archive provenance 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" || \@@ -167,7 +165,7 @@ cat > "$FIX/binaries/scan-set.tsv" <<EOF# associations=2scan_path sha256 size association_count association_kindsobjects/member $MEMBER_SHA 40 1 binary-objects/script $ASSET_SHA 20 1 ui_asset+objects/license $ASSET_SHA 20 1 runtimeEOFrun_publishfor asset in virustotal-associations.tsv virustotal-scan-set.tsv virustotal-results.tsv virustotal-evidence-checksums.txt; dodiff --git a/tests/test_windows_bundle_contract.sh b/tests/test_windows_bundle_contract.shindex 430b5ba60..3a7faf52d 100644--- a/tests/test_windows_bundle_contract.sh+++ b/tests/test_windows_bundle_contract.sh@@ -139,21 +139,16 @@ require("Makefile.cbm must not expose a Windows launcher target or variable",)-# Each archive variant is still produced through the ONE canonical packaging-# entry, so the four-file layout above governs all of them.+# Every archive is produced through the ONE canonical packaging entry, so the+# four-file layout above governs all of them. A reappearing --variant flag would+# mean the retired two-composition split is back.build_workflow = read(".github/workflows/_build.yml")-for archive, call, ui in (- ("codebase-memory-mcp-windows-amd64.zip", "scripts/package-release.sh windows amd64", False),- ("codebase-memory-mcp-ui-windows-amd64.zip",- "scripts/package-release.sh windows amd64 --variant ui", True),- ("codebase-memory-mcp-windows-arm64.zip", "scripts/package-release.sh windows arm64", False),- ("codebase-memory-mcp-ui-windows-arm64.zip",- "scripts/package-release.sh windows arm64 --variant ui", True),+for archive, call in (+ ("codebase-memory-mcp-windows-amd64.zip", "scripts/package-release.sh windows amd64"),+ ("codebase-memory-mcp-windows-arm64.zip", "scripts/package-release.sh windows arm64"),):- # The lookahead keeps a ui call from satisfying a standard check.- pattern = re.escape(call) + ("" if ui else r"(?!\s+--variant)")require(- re.search(pattern, build_workflow) is not None,+ re.search(re.escape(call) + r"(?!\s+--variant)", build_workflow) is not None,f"_build.yml must produce {archive} via the canonical packaging entry ('{call}')",)