Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
fix(packages): put every wrapper and its tests on the same base
Martin Vogel6415f94fef21
diff --git a/pkg/go/cmd/codebase-memory-mcp/main.go b/pkg/go/cmd/codebase-memory-mcp/main.goindex f0e675720..93b626a83 100644--- a/pkg/go/cmd/codebase-memory-mcp/main.go+++ b/pkg/go/cmd/codebase-memory-mcp/main.go@@ -35,9 +35,9 @@ import ()const (- repo = "DeusData/codebase-memory-mcp"- version = "0.8.1"- windowsBinaryName = "codebase-memory-mcp.exe"+ repo = "DeusData/codebase-memory-mcp"+ version = "0.8.1"+ windowsBinaryName = "codebase-memory-mcp.exe"maxRedirects = 5requestTimeout = 2 * time.Minute@@ -802,8 +802,7 @@ func extractTarGzWithLimits(if err != nil {return nil, err}- err := validateArchiveMemberNames(names, archiveNames, false)- if err != nil {+ if err := validateArchiveMemberNames(names, archiveNames, false); err != nil {return nil, err}runtimeNames := append([]string(nil), extractNames...)@@ -948,8 +947,7 @@ func extractZipWithLimits(names = append(names, name)declaredSizes[name] = declaredSize}- err := validateArchiveMemberNames(names, archiveNames, true)- if err != nil {+ if err := validateArchiveMemberNames(names, archiveNames, true); err != nil {return nil, err}runtimeNames := append([]string(nil), extractNames...)diff --git a/pkg/go/cmd/codebase-memory-mcp/main_test.go b/pkg/go/cmd/codebase-memory-mcp/main_test.goindex 083a92479..32145b49f 100644--- a/pkg/go/cmd/codebase-memory-mcp/main_test.go+++ b/pkg/go/cmd/codebase-memory-mcp/main_test.go@@ -1,197 +1,1018 @@package mainimport (+ "archive/tar"+ "archive/zip"+ "bytes"+ "compress/gzip"+ "encoding/json"+ "errors""fmt"+ "io"+ "net/http""os"+ "os/exec""path/filepath"+ "reflect"+ "runtime""strings""sync""testing"+ "time")-func TestExecutionPathForOSUsesAdjacentWindowsLauncher(t *testing.T) {- payload := filepath.Join("cache", version, windowsPayloadName)- want := filepath.Join("cache", version, windowsLauncherName)+type archiveTestRoundTripper func(*http.Request) (*http.Response, error)- if got := executionPathForOS(payload, "windows"); got != want {- t.Fatalf("Windows execution path = %q, want adjacent launcher %q", got, want)+func (transport archiveTestRoundTripper) RoundTrip(+ request *http.Request,+) (*http.Response, error) {+ return transport(request)+}++type archiveCountingBody struct {+ reader io.Reader+ read int64+}++func (body *archiveCountingBody) Read(buffer []byte) (int, error) {+ count, err := body.reader.Read(buffer)+ body.read += int64(count)+ return count, err+}++func (*archiveCountingBody) Close() error { return nil }++func assertRuntimeTag(t *testing.T, directory, binaryName, tag string) {+ t.Helper()+ contents, err := os.ReadFile(filepath.Join(directory, binaryName))+ if err != nil {+ t.Fatal(err)+ }+ if string(contents) != "binary:"+tag {+ t.Fatalf("%s = %q, want %q", binaryName, contents, "binary:"+tag)+ }+}++func writeTestRuntimeSet(t *testing.T, directory, binaryName, tag string) {+ t.Helper()+ if err := os.MkdirAll(directory, 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(+ filepath.Join(directory, binaryName), []byte("binary:"+tag), 0755,+ ); err != nil {+ t.Fatal(err)+ }+}++func TestWindowsUsesOneDirectBinary(t *testing.T) {+ binary := filepath.Join("cache", version, "ui", windowsBinaryName)+ if got := executionPathForOS(binary, "windows"); got != binary {+ t.Fatalf("Windows execution path = %q, want direct binary %q", got, binary)+ }+ if got := binaryNameForOS("windows"); got != "codebase-memory-mcp.exe" {+ t.Fatalf("Windows binary name = %q", got)}- if got := executionPathForOS(payload, "linux"); got != payload {- t.Fatalf("non-Windows execution path = %q, want payload %q", got, payload)+ source, err := os.ReadFile("main.go")+ if err != nil {+ t.Fatal(err)+ }+ for _, obsolete := range []string{"payload", "launcher"} {+ if strings.Contains(strings.ToLower(string(source)), obsolete) {+ t.Fatalf("Go wrapper still contains obsolete %q model", obsolete)+ }}}-func TestPortableMutationActionPreservesPackageManagerRefusal(t *testing.T) {+func TestCacheSensitiveMutationActionIsExplicit(t *testing.T) {cases := []struct {args []stringwant string}{{args: []string{"update", "--yes"}, want: "update"},{args: []string{"uninstall", "--yes"}, want: "uninstall"},- {args: []string{"install", "--yes"}, want: ""},+ {args: []string{"install", "--yes"}, want: "install"},{args: []string{"cli", "update"}, want: ""},+ {args: []string{"daemon", "update"}, want: ""},}-for _, testCase := range cases {- if got := portableMutationAction(testCase.args); got != testCase.want {- t.Errorf("portableMutationAction(%q) = %q, want %q", testCase.args, got, testCase.want)+ if got := runtimeMutationAction(testCase.args); got != testCase.want {+ t.Errorf(+ "runtimeMutationAction(%q) = %q, want %q",+ testCase.args,+ got,+ testCase.want,+ )}}}-func writeTestWindowsPair(t *testing.T, directory, tag string) {+func TestWrapperUninstallNeverDefaultsToItsCacheBinary(t *testing.T) {+ custom := []string{"uninstall", "--dir", filepath.Join("custom", "bin")}+ if got := nativeArgs(custom); !reflect.DeepEqual(got, custom) {+ t.Fatalf("custom uninstall args = %q, want %q", got, custom)+ }+ got := nativeArgs([]string{"uninstall", "--yes"})+ wantBase := "bin"+ if runtime.GOOS == "windows" {+ wantBase = "codebase-memory-mcp"+ }+ if len(got) != 4 || got[2] != "--dir" ||+ filepath.Base(got[3]) != wantBase {+ t.Fatalf("default uninstall args do not target managed install: %q", got)+ }+}++func writeTarGz(t *testing.T, archivePath string, names []string) {t.Helper()- if err := os.MkdirAll(directory, 0755); err != nil {+ file, err := os.Create(archivePath)+ if err != nil {t.Fatal(err)}- if err := os.WriteFile(- filepath.Join(directory, windowsLauncherName),- []byte("launcher:"+tag), 0755); err != nil {+ gz := gzip.NewWriter(file)+ tw := tar.NewWriter(gz)+ for _, name := range names {+ contents := []byte("contents:" + name)+ header := &tar.Header{+ Name: name,+ Mode: 0600,+ Size: int64(len(contents)),+ Typeflag: tar.TypeReg,+ }+ if err := tw.WriteHeader(header); err != nil {+ t.Fatal(err)+ }+ if _, err := tw.Write(contents); err != nil {+ t.Fatal(err)+ }+ }+ if err := tw.Close(); err != nil {t.Fatal(err)}- if err := os.WriteFile(- filepath.Join(directory, windowsPayloadName),- []byte("payload:"+tag), 0755); err != nil {+ if err := gz.Close(); err != nil {+ t.Fatal(err)+ }+ if err := file.Close(); err != nil {t.Fatal(err)}}-func verifyTestWindowsPair(launcherPath string) error {- launcher, err := os.ReadFile(launcherPath)- if err != nil {- return err+func TestCompressedArchiveDownloadRejectsDeclaredAndActualOverflow(t *testing.T) {+ const maxBytes = int64(8)+ priorClient := httpsOnlyClient+ defer func() { httpsOnlyClient = priorClient }()++ t.Run("declared", func(t *testing.T) {+ httpsOnlyClient = &http.Client{Transport: archiveTestRoundTripper(+ func(request *http.Request) (*http.Response, error) {+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: io.NopCloser(strings.NewReader("")),+ ContentLength: maxBytes + 1,+ Header: make(http.Header),+ Request: request,+ }, nil+ },+ )}+ destination := filepath.Join(t.TempDir(), "release.tar.gz")+ err := httpGetWithLimit(+ "https://example.invalid/release.tar.gz", destination, maxBytes,+ )+ if err == nil || !strings.Contains(err.Error(), "compressed safety limit") {+ t.Fatalf("compressed declared overflow error = %v", err)+ }+ if _, statErr := os.Stat(destination); !os.IsNotExist(statErr) {+ t.Fatal("declared oversized archive created a download")+ }+ })++ t.Run("actual", func(t *testing.T) {+ body := &archiveCountingBody{reader: bytes.NewReader(+ bytes.Repeat([]byte("x"), 1024),+ )}+ httpsOnlyClient = &http.Client{Transport: archiveTestRoundTripper(+ func(request *http.Request) (*http.Response, error) {+ return &http.Response{+ StatusCode: http.StatusOK,+ Body: body,+ ContentLength: -1,+ Header: make(http.Header),+ Request: request,+ }, nil+ },+ )}+ destination := filepath.Join(t.TempDir(), "release.tar.gz")+ err := httpGetWithLimit(+ "https://example.invalid/release.tar.gz", destination, maxBytes,+ )+ if err == nil || !strings.Contains(err.Error(), "compressed safety limit") {+ t.Fatalf("compressed actual overflow error = %v", err)+ }+ if body.read != maxBytes+1 {+ t.Fatalf("oversized response bytes consumed = %d, want %d", body.read, maxBytes+1)+ }+ if _, statErr := os.Stat(destination); !os.IsNotExist(statErr) {+ t.Fatal("rejected compressed archive left a partial download")+ }+ })+}++func testArchiveLimits(+ members int, memberBytes, expandedBytes int64,+) archiveResourceLimits {+ return archiveResourceLimits{+ compressedBytes: 1024 * 1024,+ members: members,+ memberBytes: memberBytes,+ expandedBytes: expandedBytes,}- payload, err := os.ReadFile(- filepath.Join(filepath.Dir(launcherPath), windowsPayloadName))- if err != nil {- return err+}++func TestTarArchiveRejectsMemberAndExpandedResourceOverflow(t *testing.T) {+ root := t.TempDir()+ tests := []struct {+ name string+ names []string+ limits archiveResourceLimits+ wantError string+ }{+ {+ name: "member count",+ names: []string{"one", "two", "three"},+ limits: testArchiveLimits(2, 1024, 4096),+ wantError: "member safety limit",+ },+ {+ name: "declared member bytes",+ names: []string{"oversized"},+ limits: testArchiveLimits(4, 4, 4096),+ wantError: "expanded safety limit",+ },+ {+ name: "declared aggregate bytes",+ names: []string{"one", "two"},+ limits: testArchiveLimits(4, 1024, 15),+ wantError: "aggregate expanded safety limit",+ },+ }+ for _, testCase := range tests {+ t.Run(testCase.name, func(t *testing.T) {+ archivePath := filepath.Join(root, strings.ReplaceAll(testCase.name, " ", "-")+".tar.gz")+ writeTarGz(t, archivePath, testCase.names)+ _, err := tarGzMemberNamesWithLimits(archivePath, testCase.limits)+ if err == nil || !strings.Contains(err.Error(), testCase.wantError) {+ t.Fatalf("tar resource overflow error = %v", err)+ }+ })}- const prefix = "launcher:"- if !strings.HasPrefix(string(launcher), prefix) {- return fmt.Errorf("invalid launcher test fixture")+}++func TestArchiveCopyRejectsActualMemberAggregateAndMetadataMismatch(t *testing.T) {+ tests := []struct {+ name string+ contents string+ declared int64+ actual int64+ limits archiveResourceLimits+ wantError string+ }{+ {+ name: "actual member bytes",+ contents: "12345",+ declared: 5,+ limits: testArchiveLimits(1, 4, 10),+ wantError: "actual expanded safety limit",+ },+ {+ name: "actual aggregate bytes",+ contents: "12",+ declared: 2,+ actual: 4,+ limits: testArchiveLimits(1, 10, 5),+ wantError: "aggregate actual expanded safety limit",+ },+ {+ name: "declared actual mismatch",+ contents: "123",+ declared: 2,+ limits: testArchiveLimits(1, 10, 10),+ wantError: "does not match declared size",+ },}- tag := strings.TrimPrefix(string(launcher), prefix)- if string(payload) != "payload:"+tag {- return fmt.Errorf("launcher/payload test fixture mismatch")+ for _, testCase := range tests {+ t.Run(testCase.name, func(t *testing.T) {+ actual := testCase.actual+ var output bytes.Buffer+ err := copyArchiveMemberWithLimits(+ &output,+ strings.NewReader(testCase.contents),+ "member",+ testCase.declared,+ &actual,+ testCase.limits,+ )+ if err == nil || !strings.Contains(err.Error(), testCase.wantError) {+ t.Fatalf("actual archive overflow error = %v", err)+ }+ })}- return nil}-func assertTestWindowsPair(t *testing.T, directory, tag string) {+func writeZip(t *testing.T, archivePath string, names []string) {t.Helper()- launcher, err := os.ReadFile(filepath.Join(directory, windowsLauncherName))+ file, err := os.Create(archivePath)if err != nil {t.Fatal(err)}- payload, err := os.ReadFile(filepath.Join(directory, windowsPayloadName))- if err != nil {+ zw := zip.NewWriter(file)+ for _, name := range names {+ member, err := zw.Create(name)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := member.Write([]byte("contents:" + name)); err != nil {+ t.Fatal(err)+ }+ }+ if err := zw.Close(); err != nil {t.Fatal(err)}- if string(launcher) != "launcher:"+tag || string(payload) != "payload:"+tag {- t.Fatalf("pair = %q / %q, want coherent tag %q", launcher, payload, tag)+ if err := file.Close(); err != nil {+ t.Fatal(err)}}-func TestWindowsPairPublicationRepairsCorruptAndPartialCaches(t *testing.T) {+func TestZipArchiveRejectsMemberAndExpandedResourceOverflow(t *testing.T) {+ root := t.TempDir()tests := []struct {- name string- setup func(t *testing.T, destination string)+ name string+ names []string+ limits archiveResourceLimits+ wantError string}{{- name: "corrupt launcher",- setup: func(t *testing.T, destination string) {- writeTestWindowsPair(t, destination, "old")- if err := os.WriteFile(- filepath.Join(destination, windowsLauncherName),- []byte("corrupt"), 0755); err != nil {- t.Fatal(err)- }- },+ name: "member count",+ names: []string{"one", "two", "three"},+ limits: testArchiveLimits(2, 1024, 4096),+ wantError: "member safety limit",},{- name: "corrupt payload",- setup: func(t *testing.T, destination string) {- writeTestWindowsPair(t, destination, "old")- if err := os.WriteFile(- filepath.Join(destination, windowsPayloadName),- []byte("corrupt"), 0755); err != nil {- t.Fatal(err)- }- },+ name: "declared member bytes",+ names: []string{"oversized"},+ limits: testArchiveLimits(4, 4, 4096),+ wantError: "expanded safety limit",},{- name: "launcher only",- setup: func(t *testing.T, destination string) {- if err := os.MkdirAll(destination, 0755); err != nil {- t.Fatal(err)- }- if err := os.WriteFile(- filepath.Join(destination, windowsLauncherName),- []byte("launcher:partial"), 0755); err != nil {- t.Fatal(err)- }- },+ name: "declared aggregate bytes",+ names: []string{"one", "two"},+ limits: testArchiveLimits(4, 1024, 15),+ wantError: "aggregate expanded safety limit",},}-for _, testCase := range tests {t.Run(testCase.name, func(t *testing.T) {- root := t.TempDir()- source := filepath.Join(root, "source")- destination := filepath.Join(root, "destination")- writeTestWindowsPair(t, source, "candidate")- testCase.setup(t, destination)-- if err := installWindowsPairAtomicallyWithVerifier(- source, destination, verifyTestWindowsPair); err != nil {+ archivePath := filepath.Join(root, strings.ReplaceAll(testCase.name, " ", "-")+".zip")+ writeZip(t, archivePath, testCase.names)+ destination := filepath.Join(root, strings.ReplaceAll(testCase.name, " ", "-")+"-extract")+ if err := os.Mkdir(destination, 0755); err != nil {t.Fatal(err)}- assertTestWindowsPair(t, destination, "candidate")+ _, err := extractZipWithLimits(+ archivePath,+ destination,+ testCase.names,+ testCase.names[:1],+ testCase.limits,+ )+ if err == nil || !strings.Contains(err.Error(), testCase.wantError) {+ t.Fatalf("zip resource overflow error = %v", err)+ }})}}-func TestWindowsPairPublicationSerializesConcurrentCandidates(t *testing.T) {+func verifyTestBinary(path string) error {+ contents, err := os.ReadFile(path)+ if err != nil {+ return err+ }+ if !strings.HasPrefix(string(contents), "binary:") {+ return fmt.Errorf("invalid test binary")+ }+ return nil+}++func TestMutationSnapshotReleasesCacheLockAndCleansAfterLaunchFailure(t *testing.T) {+ directory := t.TempDir()+ binary := "codebase-memory-mcp"+ executable := filepath.Join(directory, binary)+ writeTestRuntimeSet(t, directory, binary, "cached")+ var snapshotExecutable string+ runnerCalled := false+ err := execBinaryWithRuntimeLockAndRunner(+ executable,+ []string{"install", "--yes"},+ verifyTestBinary,+ func(candidate string, args []string) error {+ runnerCalled = true+ snapshotExecutable = candidate+ if reflect.DeepEqual(args, []string{"install", "--yes"}) == false {+ t.Fatalf("snapshot mutation args = %q", args)+ }+ if filepath.Dir(candidate) == directory {+ t.Fatal("mutation launched from the shared package cache")+ }+ status, err := os.Lstat(filepath.Dir(candidate))+ if err != nil {+ t.Fatal(err)+ }+ if !status.IsDir() ||+ (runtime.GOOS != "windows" && status.Mode().Perm()&0077 != 0) {+ t.Fatalf("mutation snapshot mode = %v, want owner-private", status.Mode())+ }+ assertRuntimeTag(+ t, filepath.Dir(candidate), binary, "cached",+ )+ if _, err := os.Stat(filepath.Join(+ directory, runtimeSetLockName,+ )); !os.IsNotExist(err) {+ t.Fatal("cache lock remained held when snapshot runner started")+ }+ if err := os.WriteFile(+ executable, []byte("binary:successor"), 0755,+ ); err != nil {+ t.Fatal(err)+ }+ contents, err := os.ReadFile(candidate)+ if err != nil {+ t.Fatal(err)+ }+ if string(contents) != "binary:cached" {+ t.Fatalf("cache mutation changed private snapshot: %q", contents)+ }+ return fmt.Errorf("injected snapshot launch failure")+ },+ )+ if err == nil || !strings.Contains(err.Error(), "injected snapshot launch failure") {+ t.Fatalf("mutation launch failure = %v", err)+ }+ if !runnerCalled {+ t.Fatal("verified mutation snapshot was not launched")+ }+ if _, err := os.Stat(filepath.Dir(snapshotExecutable)); !os.IsNotExist(err) {+ t.Fatal("failed mutation left its private runtime snapshot")+ }+ if _, err := os.Stat(filepath.Join(+ directory, runtimeSetLockName,+ )); !os.IsNotExist(err) {+ t.Fatal("failed mutation left the package-cache lock")+ }+}++func TestMutationSnapshotEnvironmentIgnoresExternalAssetOverrides(t *testing.T) {+ t.Setenv("CBM_ASSETS_DIR", filepath.Join(t.TempDir(), "integrations"))+ t.Setenv("CBM_UI_ASSETS_DIR", filepath.Join(t.TempDir(), "ui"))+ for _, entry := range mutationSnapshotEnvironment() {+ name := entry+ if separator := strings.IndexByte(entry, '='); separator >= 0 {+ name = entry[:separator]+ }+ if strings.EqualFold(name, "CBM_ASSETS_DIR") ||+ strings.EqualFold(name, "CBM_UI_ASSETS_DIR") {+ t.Fatalf("mutation snapshot environment retained %q", entry)+ }+ }+}++func TestMutationSnapshotRejectsExplicitTargetOverlappingCache(t *testing.T) {+ directory := t.TempDir()+ executable := filepath.Join(directory, "codebase-memory-mcp")+ for _, args := range [][]string{+ {"install", "--dir", directory},+ {"uninstall", "--dir=" + directory},+ } {+ runnerCalled := false+ err := execBinaryWithRuntimeLockAndRunner(+ executable,+ args,+ nil,+ func(string, []string) error {+ runnerCalled = true+ return nil+ },+ )+ if err == nil || !strings.Contains(err.Error(), "overlaps the shared package cache") {+ t.Fatalf("overlapping mutation target error = %v", err)+ }+ if runnerCalled {+ t.Fatal("overlapping cache mutation target was launched")+ }+ }+}++func TestMutationSnapshotVerifierFailureNeverLaunches(t *testing.T) {+ directory := t.TempDir()+ binary := "codebase-memory-mcp"+ executable := filepath.Join(directory, binary)+ writeTestRuntimeSet(t, directory, binary, "cached")+ verifierCalls := 0+ verifier := func(path string) error {+ verifierCalls+++ if filepath.Dir(path) != directory {+ return fmt.Errorf("injected private snapshot verification failure")+ }+ return verifyTestBinary(path)+ }+ runnerCalled := false+ err := execBinaryWithRuntimeLockAndRunner(+ executable,+ []string{"install", "--yes"},+ verifier,+ func(string, []string) error {+ runnerCalled = true+ return nil+ },+ )+ if err == nil || !strings.Contains(err.Error(), "failed verification") {+ t.Fatalf("snapshot verifier failure = %v", err)+ }+ if verifierCalls != 2 {+ t.Fatalf("snapshot verifier calls = %d, want source and snapshot", verifierCalls)+ }+ if runnerCalled {+ t.Fatal("mutation runner was invoked after snapshot verification failure")+ }+ if _, err := os.Stat(filepath.Join(+ directory, runtimeSetLockName,+ )); !os.IsNotExist(err) {+ t.Fatal("snapshot verification failure left the package-cache lock")+ }+}++func TestMutationSnapshotCleanupFailurePreservesNativeResult(t *testing.T) {+ const exitHelper = "CBM_GO_MUTATION_EXIT_HELPER"+ if os.Getenv(exitHelper) == "1" {+ os.Exit(7)+ }+ exitCommand := exec.Command(+ os.Args[0],+ "-test.run=^TestMutationSnapshotCleanupFailurePreservesNativeResult$",+ )+ exitCommand.Env = append(os.Environ(), exitHelper+"=1")+ nativeErr := exitCommand.Run()+ exitErr, ok := nativeErr.(*exec.ExitError)+ if !ok {+ t.Fatalf("exit helper error = %T %v", nativeErr, nativeErr)+ }++ priorCleanup := runtimeMutationSnapshotCleanup+ defer func() { runtimeMutationSnapshotCleanup = priorCleanup }()+ runtimeMutationSnapshotCleanup = func(path string) error {+ if err := os.RemoveAll(path); err != nil {+ return err+ }+ return errors.New("injected private snapshot cleanup failure")+ }+ for _, testCase := range []struct {+ name string+ runnerErr error+ wantResult error+ }{+ {name: "native success remains success"},+ {name: "native exit error identity survives", runnerErr: exitErr, wantResult: exitErr},+ } {+ t.Run(testCase.name, func(t *testing.T) {+ directory := t.TempDir()+ binary := "codebase-memory-mcp"+ writeTestRuntimeSet(t, directory, binary, "cached")+ result := execBinaryWithRuntimeLockAndRunner(+ filepath.Join(directory, binary),+ []string{"install", "--yes"},+ verifyTestBinary,+ func(string, []string) error { return testCase.runnerErr },+ )+ if result != testCase.wantResult {+ t.Fatalf("native result identity changed: got %v, want %v", result, testCase.wantResult)+ }+ if exitErr != nil && testCase.wantResult != nil {+ var recovered *exec.ExitError+ if !errors.As(result, &recovered) || recovered != exitErr {+ t.Fatal("native ExitError was not preserved through cleanup failure")+ }+ }+ })+ }+}++func TestRuntimeSetLockReclaimsOnlyDefinitelyDeadOwner(t *testing.T) {+ destination := t.TempDir()+ lockPath := filepath.Join(destination, runtimeSetLockName)+ if err := os.Mkdir(lockPath, 0700); err != nil {+ t.Fatal(err)+ }+ ownerToken := strings.Repeat("a", runtimeSetLockTokenSize*2)+ if err := writeRuntimeSetLockOwner(lockPath, ownerToken); err != nil {+ t.Fatal(err)+ }+ contenderToken := strings.Repeat("b", runtimeSetLockTokenSize*2)+ priorProcessAlive := runtimeSetProcessAlive+ defer func() { runtimeSetProcessAlive = priorProcessAlive }()++ runtimeSetProcessAlive = func(int) bool { return true }+ if runtimeSetTryReclaimLock(lockPath, contenderToken) {+ t.Fatal("runtime-set lock reclaimed an owner that may still be live")+ }+ if _, err := os.Stat(lockPath); err != nil {+ t.Fatalf("live owner's runtime-set lock was damaged: %v", err)+ }++ runtimeSetProcessAlive = func(int) bool { return false }+ if !runtimeSetTryReclaimLock(lockPath, contenderToken) {+ t.Fatal("runtime-set lock did not reclaim a definitely dead owner")+ }+ if _, err := os.Stat(lockPath); !os.IsNotExist(err) {+ t.Fatal("reclaimed dead-owner runtime-set lock still exists")+ }+}++func TestRuntimeSetLiveOwnerSkipsIdentityCapture(t *testing.T) {+ destination := t.TempDir()+ lock, err := acquireRuntimeSetLock(destination)+ if err != nil {+ t.Fatal(err)+ }+ released := false+ defer func() {+ if !released {+ if err := releaseRuntimeSetLock(lock); err != nil {+ t.Errorf("release live runtime-set lock: %v", err)+ }+ }+ }()++ priorObserver := runtimeSetLockCaptureObserver+ priorProcessAlive := runtimeSetProcessAlive+ defer func() {+ runtimeSetLockCaptureObserver = priorObserver+ runtimeSetProcessAlive = priorProcessAlive+ }()+ captures := 0+ runtimeSetLockCaptureObserver = func() { captures++ }+ runtimeSetProcessAlive = func(int) bool { return true }++ contenderToken := strings.Repeat("b", runtimeSetLockTokenSize*2)+ if runtimeSetTryReclaimLock(lock.path, contenderToken) {+ t.Fatal("runtime-set lock reclaimed a proven-live owner")+ }+ if captures != 0 {+ t.Fatalf("live runtime-set lock identity was captured %d times", captures)+ }+ if err := releaseRuntimeSetLock(lock); err != nil {+ t.Fatalf("release live runtime-set lock: %v", err)+ }+ released = true+}++func TestRuntimeSetLockReclaimsOnlyStaleOwnerlessDirectory(t *testing.T) {+ destination := t.TempDir()+ lockPath := filepath.Join(destination, runtimeSetLockName)+ if err := os.Mkdir(lockPath, 0700); err != nil {+ t.Fatal(err)+ }+ contenderToken := strings.Repeat("c", runtimeSetLockTokenSize*2)+ if runtimeSetTryReclaimLock(lockPath, contenderToken) {+ t.Fatal("fresh ownerless runtime-set lock was reclaimed")+ }+ staleTime := time.Now().Add(-runtimeSetOwnerlessStale - time.Second)+ if err := os.Chtimes(lockPath, staleTime, staleTime); err != nil {+ t.Fatal(err)+ }+ if !runtimeSetTryReclaimLock(lockPath, contenderToken) {+ t.Fatal("stale ownerless runtime-set lock was not reclaimed")+ }+ if _, err := os.Stat(lockPath); !os.IsNotExist(err) {+ t.Fatal("reclaimed ownerless runtime-set lock still exists")+ }+}++func TestExpiredLeaseNeverStealsProvenLiveOwner(t *testing.T) {+ destination := t.TempDir()+ lockPath := filepath.Join(destination, runtimeSetLockName)+ record := runtimeSetLockOwnerRecord{+ PID: os.Getpid(), Token: strings.Repeat("a", runtimeSetLockTokenSize*2),+ LeaseExpires: time.Now().Add(-time.Second).UnixMilli(),+ }+ contents, err := json.Marshal(record)+ if err != nil {+ t.Fatal(err)+ }+ contents = append(contents, '\n')+ if err := os.WriteFile(lockPath, contents, 0600); err != nil {+ t.Fatal(err)+ }+ before, err := os.Lstat(lockPath)+ if err != nil {+ t.Fatal(err)+ }+ priorProcessAlive := runtimeSetProcessAlive+ defer func() { runtimeSetProcessAlive = priorProcessAlive }()+ runtimeSetProcessAlive = func(int) bool { return true }+ contender := strings.Repeat("b", runtimeSetLockTokenSize*2)+ if runtimeSetTryReclaimLock(lockPath, contender) {+ t.Fatal("runtime-set lock stole an expired lease from a proven-live owner")+ }+ after, err := os.Lstat(lockPath)+ if err != nil {+ t.Fatalf("live owner's expired lock was removed: %v", err)+ }+ if !runtimeSetSameLockObject(before, after) {+ t.Fatal("live owner's expired lock identity changed")+ }+ afterContents, err := os.ReadFile(lockPath)+ if err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(afterContents, contents) {+ t.Fatalf("live owner's expired lock contents changed: %q", afterContents)+ }+}++func TestLiveLegacyLockIsNotReclaimedSolelyByAge(t *testing.T) {+ destination := t.TempDir()+ lockPath := filepath.Join(destination, runtimeSetLockName)+ if err := os.Mkdir(lockPath, 0700); err != nil {+ t.Fatal(err)+ }+ if err := writeRuntimeSetLockOwner(+ lockPath, strings.Repeat("a", runtimeSetLockTokenSize*2),+ ); err != nil {+ t.Fatal(err)+ }+ stale := time.Now().Add(-runtimeSetLegacyStale - time.Second)+ if err := os.Chtimes(lockPath, stale, stale); err != nil {+ t.Fatal(err)+ }+ priorProcessAlive := runtimeSetProcessAlive+ defer func() { runtimeSetProcessAlive = priorProcessAlive }()+ runtimeSetProcessAlive = func(int) bool { return true }+ if runtimeSetTryReclaimLock(+ lockPath, strings.Repeat("b", runtimeSetLockTokenSize*2),+ ) {+ t.Fatal("live legacy runtime-set lock was reclaimed solely by age")+ }+ if _, err := os.Stat(lockPath); err != nil {+ t.Fatalf("live legacy runtime-set lock was damaged: %v", err)+ }+}++func TestStalledRuntimeLockCreatorNeverDeletesSuccessor(t *testing.T) {+ destination := t.TempDir()+ var successor *runtimeSetLock+ var successorErr error+ priorObserver := runtimeSetLockClaimObserver+ defer func() { runtimeSetLockClaimObserver = priorObserver }()+ runtimeSetLockClaimObserver = func() error {+ runtimeSetLockClaimObserver = nil+ successor, successorErr = acquireRuntimeSetLock(destination)+ return fmt.Errorf("injected stalled creator abort")+ }++ if first, err := acquireRuntimeSetLock(destination); err == nil {+ _ = releaseRuntimeSetLock(first)+ t.Fatal("stalled creator unexpectedly acquired over its successor")+ } else if !strings.Contains(err.Error(), "stalled creator abort") {+ t.Fatalf("stalled creator failed for wrong reason: %v", err)+ }+ if successorErr != nil || successor == nil {+ t.Fatalf("successor did not acquire reclaimed lock: %v", successorErr)+ }+ if _, err := os.Stat(successor.path); err != nil {+ t.Fatalf("failed creator deleted successor lock: %v", err)+ }+ if err := releaseRuntimeSetLock(successor); err != nil {+ t.Fatal(err)+ }+}++func TestRuntimeSetLockReleaseRetiresDescriptor(t *testing.T) {+ destination := t.TempDir()+ lock, err := acquireRuntimeSetLock(destination)+ if err != nil {+ t.Fatal(err)+ }+ if lock.file == nil {+ t.Fatal("acquired runtime-set lock has no writable descriptor")+ }+ if err := releaseRuntimeSetLock(lock); err != nil {+ t.Fatal(err)+ }+ if lock.file != nil {+ t.Fatal("released runtime-set lock retained its closed descriptor")+ }+ if _, err := os.Lstat(lock.path); !os.IsNotExist(err) {+ t.Fatalf("released runtime-set lock remained at its canonical path: %v", err)+ }+}++func TestWindowsLongRuntimePathPublishesAndBecomesReady(t *testing.T) {+ if runtime.GOOS != "windows" {+ t.Skip("Windows long-path regression")+ }root := t.TempDir()- destination := filepath.Join(root, "destination")- if err := os.MkdirAll(destination, 0755); err != nil {- t.Fatal(err)- }- sources := []string{filepath.Join(root, "source-a"), filepath.Join(root, "source-b")}- writeTestWindowsPair(t, sources[0], "a")- writeTestWindowsPair(t, sources[1], "b")-- start := make(chan struct{})- errors := make(chan error, len(sources))- var wait sync.WaitGroup- for _, source := range sources {- wait.Add(1)- go func(candidate string) {- defer wait.Done()- <-start- errors <- installWindowsPairAtomicallyWithVerifier(- candidate, destination, verifyTestWindowsPair)- }(source)- }- close(start)- wait.Wait()- close(errors)- for err := range errors {+ source := filepath.Join(root, "source")+ destination := filepath.Join(root, "runtime")+ for len(destination) <= 300 {+ destination = filepath.Join(+ destination, "long-runtime-directory-segment",+ )+ }+ if len(destination) <= 260 {+ t.Fatalf("test runtime path is not long: %d", len(destination))+ }+ binary := windowsBinaryName+ writeTestRuntimeSet(t, source, binary, "long-path")+ if err := publishRuntimeSetWithRecovery(+ source, destination, binary, verifyTestBinary,+ ); err != nil {+ t.Fatalf("publication under a long Windows runtime path failed: %v", err)+ }+ ready, err := runtimeSetReadyLocked(+ destination, binary, verifyTestBinary,+ )+ if err != nil {+ t.Fatalf("locked readiness under a long Windows runtime path failed: %v", err)+ }+ if !ready {+ t.Fatal("published long-path Windows runtime set was not ready")+ }+}++func TestOrphanReconciliationRejectsMultiplyLinkedBackupMembers(t *testing.T) {+ directory := t.TempDir()+ binary := "codebase-memory-mcp"+ backup := filepath.Join(+ directory, runtimeBackupPrefix+strings.Repeat("a", 32),+ )+ if err := os.Mkdir(backup, 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(+ filepath.Join(backup, runtimeBackupRetired), nil, 0600,+ ); err != nil {+ t.Fatal(err)+ }+ member := filepath.Join(backup, binary)+ if err := os.WriteFile(member, []byte("binary:old"), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.Link(+ member, filepath.Join(directory, "backup-hardlink-copy"),+ ); err != nil {+ t.Skipf("filesystem does not support hard links: %v", err)+ }++ ready, err := runtimeSetReadyLocked(+ directory, binary, verifyTestBinary,+ )+ if err == nil || !strings.Contains(+ err.Error(), "unsafe package-cache backup member",+ ) {+ t.Fatalf("unsafe orphan reconciliation = (%v, %v)", ready, err)+ }+ if _, err := os.Stat(backup); err != nil {+ t.Fatalf("unsafe backup was mutated: %v", err)+ }+ if _, err := os.Stat(filepath.Join(+ directory, runtimeSetLockName,+ )); !os.IsNotExist(err) {+ t.Fatal("runtime-set lock survived rejected orphan reconciliation")+ }+}++func TestRuntimeSetLockSerializesProcesses(t *testing.T) {+ const helperEnv = "CBM_GO_RUNTIME_LOCK_HELPER"+ if os.Getenv(helperEnv) == "1" {+ destination := os.Getenv("CBM_GO_RUNTIME_LOCK_DIRECTORY")+ waitingPath := os.Getenv("CBM_GO_RUNTIME_LOCK_WAITING")+ acquiredPath := os.Getenv("CBM_GO_RUNTIME_LOCK_ACQUIRED")+ var waitOnce sync.Once+ runtimeSetLockWaitObserver = func() {+ waitOnce.Do(func() {+ if err := os.WriteFile(waitingPath, []byte("waiting"), 0600); err != nil {+ t.Fatal(err)+ }+ })+ }+ lock, err := acquireRuntimeSetLock(destination)if err != nil {t.Fatal(err)}+ if err := os.WriteFile(acquiredPath, []byte("acquired"), 0600); err != nil {+ _ = releaseRuntimeSetLock(lock)+ t.Fatal(err)+ }+ if err := releaseRuntimeSetLock(lock); err != nil {+ t.Fatal(err)+ }+ return}- if err := verifyTestWindowsPair(- filepath.Join(destination, windowsLauncherName)); err != nil {++ destination := t.TempDir()+ waitingPath := filepath.Join(t.TempDir(), "waiting")+ acquiredPath := filepath.Join(t.TempDir(), "acquired")+ lock, err := acquireRuntimeSetLock(destination)+ if err != nil {t.Fatal(err)}- launcher, err := os.ReadFile(filepath.Join(destination, windowsLauncherName))- if err != nil {+ released := false+ defer func() {+ if !released {+ _ = releaseRuntimeSetLock(lock)+ }+ }()++ cmd := exec.Command(os.Args[0], "-test.run=^TestRuntimeSetLockSerializesProcesses$")+ cmd.Env = append(+ os.Environ(),+ helperEnv+"=1",+ "CBM_GO_RUNTIME_LOCK_DIRECTORY="+destination,+ "CBM_GO_RUNTIME_LOCK_WAITING="+waitingPath,+ "CBM_GO_RUNTIME_LOCK_ACQUIRED="+acquiredPath,+ )+ var stdout bytes.Buffer+ var stderr bytes.Buffer+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ waitResult := make(chan error, 1)+ go func() { waitResult <- cmd.Wait() }()+ childFinished := false+ defer func() {+ if !childFinished {+ _ = cmd.Process.Kill()+ <-waitResult+ }+ }()++ deadline := time.Now().Add(5 * time.Second)+ for {+ select {+ case err := <-waitResult:+ childFinished = true+ t.Fatalf(+ "runtime-set lock helper exited before waiting: %v\nstdout: %s\nstderr: %s",+ err,+ stdout.String(),+ stderr.String(),+ )+ default:+ }+ if _, err := os.Stat(waitingPath); err == nil {+ break+ } else if !os.IsNotExist(err) {+ t.Fatal(err)+ }+ if !time.Now().Before(deadline) {+ _ = cmd.Process.Kill()+ <-waitResult+ childFinished = true+ t.Fatalf(+ "child did not report waiting on parent lock\nstdout: %s\nstderr: %s",+ stdout.String(),+ stderr.String(),+ )+ }+ time.Sleep(5 * time.Millisecond)+ }+ if _, err := os.Stat(acquiredPath); err == nil {+ t.Fatal("child acquired the runtime-set lock while the parent owned it")+ } else if !os.IsNotExist(err) {t.Fatal(err)}- tag := strings.TrimPrefix(string(launcher), "launcher:")- if tag != "a" && tag != "b" {- t.Fatalf("unexpected concurrent winner tag %q", tag)+ if err := releaseRuntimeSetLock(lock); err != nil {+ t.Fatal(err)+ }+ released = true+ select {+ case err := <-waitResult:+ childFinished = true+ if err != nil {+ t.Fatalf(+ "runtime-set lock helper failed: %v\nstdout: %s\nstderr: %s",+ err,+ stdout.String(),+ stderr.String(),+ )+ }+ case <-time.After(5 * time.Second):+ _ = cmd.Process.Kill()+ <-waitResult+ childFinished = true+ t.Fatal("child did not acquire the released runtime-set lock")+ }+ if _, err := os.Stat(acquiredPath); err != nil {+ t.Fatalf("child never acquired the released runtime-set lock: %v", err)}- assertTestWindowsPair(t, destination, tag)}diff --git a/pkg/go/codebase-memory-mcp b/pkg/go/codebase-memory-mcpnew file mode 100644index 000000000..f8ea349b2Binary files /dev/null and b/pkg/go/codebase-memory-mcp differdiff --git a/pkg/npm/bin.js b/pkg/npm/bin.jsindex e467981be..8b7d82e09 100644--- a/pkg/npm/bin.js+++ b/pkg/npm/bin.js@@ -4,34 +4,30 @@// If the binary is missing (e.g. --ignore-scripts), attempts a one-time download.const path = require('path');-const os = require('os');-const { spawn, spawnSync } = require('child_process');-const {- acquireRuntimeLock,- refreshRuntimeLock,- releaseRuntimeLock,- runtimeSetReady,- runtimeSetReadyLocked,-} = require('./install.js');+const fs = require('fs');+const { spawnSync } = require('child_process');const isWindows = process.platform === 'win32';-const variant = (process.env.CBM_VARIANT || '').toLowerCase() === 'ui'- ? 'ui'- : 'standard';-// npm is a portable one-shot wrapper. Every platform ships exactly one binary,-// which is executed directly beside its authenticated runtime sidecars.+// npm is a portable one-shot wrapper. Every platform ships exactly ONE binary,+// so the cached file is the executed file — there is no launcher pair to keep+// in sync and no adjacent payload to validate.const binName = isWindows ? 'codebase-memory-mcp.exe' : 'codebase-memory-mcp';-const binDir = path.join(__dirname, 'bin', variant);-const binPath = path.join(binDir, binName);+const binPath = path.join(__dirname, 'bin', binName);const executionPath = binPath;-const cacheReady = () => runtimeSetReadyLocked(binDir, binName, variant);+const cacheReady = () => {+ if (!fs.existsSync(binPath)) {+ return false;+ }+ if (!isWindows) return true;+ // A cached Windows binary that cannot report its own version is not usable.+ const probe = spawnSync(binPath, ['--version'], {+ stdio: 'ignore',+ timeout: 15_000,+ windowsHide: true,+ });+ return !probe.error && probe.status === 0;+};-function main() {-const requestedMutation = runtimeMutationAction(process.argv.slice(2));-if (requestedMutation === 'update') {- printUpdateGuidance();- process.exit(2);-}if (!cacheReady()) {// Binary missing — try running the install script (handles --ignore-scripts case)process.stderr.write('codebase-memory-mcp: binary not found, downloading...\n');@@ -47,105 +43,17 @@ if (!cacheReady()) {}}-function runtimeMutationAction(args) {+function portableMutationAction(args) {for (const argument of args) {- if (argument === '--help' || argument === '-h' || argument === '--version') {+ if (['cli', 'hook-augment', 'config', 'install', '--help', '-h', '--version'].includes(argument)) {return null;}- if (argument.startsWith('-')) continue;- if (argument === 'install' || argument === 'update' || argument === 'uninstall') {- return argument;- }- if (argument === 'cli' || argument === 'hook-augment' || argument === 'config') {- return null;- }- return null;+ if (argument === 'update' || argument === 'uninstall') return argument;}return null;}-function defaultManagedInstallDir() {- if (!isWindows) return path.join(os.homedir(), '.local', 'bin');- const localAppData = process.env.LOCALAPPDATA ||- path.join(os.homedir(), 'AppData', 'Local');- return path.join(localAppData, 'Programs', 'codebase-memory-mcp');-}--function nativeArgs(args) {- const result = [...args];- if (runtimeMutationAction(result) === 'uninstall' &&- !result.some((argument) => argument === '--dir' || argument.startsWith('--dir='))) {- result.push('--dir', defaultManagedInstallDir());- }- return result;-}--function printUpdateGuidance() {- process.stderr.write(- 'This npm copy is maintained by npm. Update it with ' +- '"npm install codebase-memory-mcp@latest" (add -g for a global install). ' +- 'For a managed standalone installation, run ' +- '"codebase-memory-mcp install --yes".\n',- );-}--const forwardedArgs = nativeArgs(process.argv.slice(2));-const mutation = requestedMutation;--if (mutation === 'install' || mutation === 'uninstall') {- const lock = acquireRuntimeLock(binDir);- let heartbeatError = null;- try {- refreshRuntimeLock(lock);- if (!runtimeSetReady(binDir, binName, variant)) {- throw new Error('cached runtime assets changed before mutation launch');- }- } catch (error) {- try { releaseRuntimeLock(lock); } catch (_) { /* preserve first error */ }- process.stderr.write(`codebase-memory-mcp: ${error.message}\n`);- process.exit(1);- }- let child = null;- const heartbeat = setInterval(() => {- try {- refreshRuntimeLock(lock);- } catch (error) {- heartbeatError = error;- if (child) child.kill();- }- }, 20_000);- child = spawn(executionPath, forwardedArgs, {- stdio: 'inherit',- windowsHide: false,- });- child.on('error', (error) => {- clearInterval(heartbeat);- try { releaseRuntimeLock(lock); } catch (_) { /* report spawn error */ }- process.stderr.write(`codebase-memory-mcp: ${error.message}\n`);- process.exit(1);- });- child.on('close', (status) => {- clearInterval(heartbeat);- let releaseError = heartbeatError;- try { releaseRuntimeLock(lock); } catch (error) { releaseError ||= error; }- if (releaseError) {- process.stderr.write(`codebase-memory-mcp: ${releaseError.message}\n`);- process.exit(1);- }- if (isWindows && status !== 0 && mutation === 'uninstall') {- process.stderr.write(- 'This npm Windows copy is portable. Use "npm uninstall codebase-memory-mcp" ' +- 'for package maintenance (add -g for a global install). ' +- 'To create or repair a managed standalone installation, run ' +- '"codebase-memory-mcp install --yes".\n',- );- }- process.exit(status ?? 0);- });- return;-}--const result = spawnSync(executionPath, forwardedArgs, {+const result = spawnSync(executionPath, process.argv.slice(2), {stdio: 'inherit',windowsHide: false,});@@ -155,7 +63,19 @@ if (result.error) {process.exit(1);}-process.exit(result.status ?? 0);+const mutation = isWindows && result.status !== 0+ ? portableMutationAction(process.argv.slice(2))+ : null;+if (mutation) {+ const packageCommand = mutation === 'update'+ ? 'npm install codebase-memory-mcp@latest'+ : 'npm uninstall codebase-memory-mcp';+ process.stderr.write(+ `This npm Windows copy is portable. Use "${packageCommand}" for package ` ++ 'maintenance (add -g for a global install), or run ' ++ '"codebase-memory-mcp install --yes" once for a managed install with its ' ++ 'own install.ps1 for updates.\n',+ );}-main();+process.exit(result.status ?? 0);diff --git a/pkg/pypi/tests/test_cli.py b/pkg/pypi/tests/test_cli.pyindex 4fe297689..930783d01 100644--- a/pkg/pypi/tests/test_cli.py+++ b/pkg/pypi/tests/test_cli.py@@ -1,6 +1,18 @@+import errno+import hashlib+import json+import os+import stat+import subprocessimport sys+import tarfile+import tempfile+import threading+import timeimport unittest-from pathlib import Path+import zipfile+from pathlib import Path, PureWindowsPath+from unittest import mockPACKAGE_ROOT = Path(__file__).resolve().parents[1]@@ -22,15 +34,491 @@ class BinarySelectionTests(unittest.TestCase):self.assertEqual(_cli._execution_path(binary, "linux"), binary)- def test_portable_mutation_guidance_classification_is_preserved(self):- self.assertEqual(_cli._portable_mutation_action(["update"]), "update")+ def test_cache_sensitive_mutation_classification_is_explicit(self):+ self.assertEqual(_cli._runtime_mutation_action(["update"]), "update")self.assertEqual(- _cli._portable_mutation_action(["uninstall", "--yes"]),+ _cli._runtime_mutation_action(["uninstall", "--yes"]),"uninstall",)- self.assertIsNone(_cli._portable_mutation_action(["install", "--yes"]))- self.assertIsNone(_cli._portable_mutation_action(["cli", "update"]))+ self.assertEqual(+ _cli._runtime_mutation_action(["install", "--yes"]), "install"+ )+ self.assertIsNone(_cli._runtime_mutation_action(["cli", "update"]))+ self.assertIsNone(_cli._runtime_mutation_action(["daemon", "update"]))++ def test_wrapper_uninstall_never_defaults_to_its_cache_binary(self):+ linux_home = Path("fixtures") / "linux-home"+ windows_local_app_data = Path("fixtures") / "windows-local-app-data"+ defaults = (+ (+ "linux",+ linux_home / ".local" / "bin",+ mock.patch.object(Path, "home", return_value=linux_home),+ ),+ (+ "win32",+ windows_local_app_data+ / "Programs"+ / "codebase-memory-mcp",+ mock.patch.dict(+ os.environ,+ {"LOCALAPPDATA": str(windows_local_app_data)},+ ),+ ),+ )+ for platform_name, expected, path_fixture in defaults:+ with self.subTest(platform=platform_name), mock.patch.object(+ _cli.sys, "platform", platform_name+ ), path_fixture:+ self.assertEqual(+ _cli._native_args(["uninstall", "--yes"]),+ ["uninstall", "--yes", "--dir", str(expected)],+ )++ explicit_dir = Path("fixtures") / "explicit-install"+ for platform_name in ("linux", "win32"):+ with self.subTest(+ platform=platform_name, explicit_dir=True+ ), mock.patch.object(_cli.sys, "platform", platform_name):+ self.assertEqual(+ _cli._native_args(+ ["uninstall", "--dir", str(explicit_dir)]+ ),+ ["uninstall", "--dir", str(explicit_dir)],+ )++ def test_release_archives_carry_no_sidecars(self):+ # The binary is self-contained; a returning sidecar would silently make+ # `pip install` reject every archive against this exact-set allowlist.+ for names in (_cli._WINDOWS_ARCHIVE_NAMES, _cli._UNIX_ARCHIVE_NAMES):+ self.assertNotIn("cbm-integrations.json", names)+ self.assertFalse([n for n in names if n.startswith("cbm-ui-")])+ self.assertEqual(len(names), 4)++ def test_update_guidance_uses_pip_and_names_managed_install(self):+ with mock.patch.object(_cli.sys, "argv", ["cbm", "update"]), \+ mock.patch.object(_cli, "_version", return_value="0.8.1"), \+ mock.patch("sys.stderr") as stderr:+ with self.assertRaisesRegex(SystemExit, "2"):+ _cli.main()++ output = "".join(call.args[0] for call in stderr.write.call_args_list)+ self.assertIn(+ "python -m pip install --upgrade codebase-memory-mcp", output+ )+ self.assertIn("codebase-memory-mcp install --yes", output)+ self.assertNotIn("install.sh", output)+++class ProcessLivenessTests(unittest.TestCase):+ def test_windows_probe_never_calls_os_kill(self):+ with mock.patch.object(_cli.os, "name", "nt"), mock.patch.object(+ _cli,+ "_windows_process_is_alive",+ return_value=True,+ create=True,+ ) as windows_probe, mock.patch.object(+ _cli.os,+ "kill",+ side_effect=AssertionError("Windows must not call os.kill"),+ ):+ self.assertTrue(_cli._process_is_alive(1234))++ windows_probe.assert_called_once_with(1234)++ def test_windows_wait_result_distinguishes_dead_and_live_processes(self):+ cases = (+ (_cli._WINDOWS_WAIT_OBJECT_0, False),+ (_cli._WINDOWS_WAIT_TIMEOUT, True),+ (0xFFFFFFFF, True),+ )+ for wait_result, expected in cases:+ with self.subTest(wait_result=wait_result):+ kernel32 = mock.Mock()+ kernel32.OpenProcess.return_value = 123+ kernel32.WaitForSingleObject.return_value = wait_result+ with mock.patch.object(+ _cli,+ "_windows_process_api",+ return_value=(kernel32, mock.Mock()),+ ):+ self.assertEqual(+ _cli._windows_process_is_alive(4567), expected+ )++ kernel32.OpenProcess.assert_called_once_with(+ _cli._WINDOWS_SYNCHRONIZE, False, 4567+ )+ kernel32.WaitForSingleObject.assert_called_once_with(123, 0)+ kernel32.CloseHandle.assert_called_once_with(123)++ def test_windows_open_failure_only_treats_missing_pid_as_dead(self):+ cases = (+ (_cli._WINDOWS_ERROR_INVALID_PARAMETER, False),+ (5, True),+ )+ for error, expected in cases:+ with self.subTest(error=error):+ kernel32 = mock.Mock()+ kernel32.OpenProcess.return_value = 0+ get_last_error = mock.Mock(return_value=error)+ with mock.patch.object(+ _cli,+ "_windows_process_api",+ return_value=(kernel32, get_last_error),+ ):+ self.assertEqual(+ _cli._windows_process_is_alive(4567), expected+ )++ get_last_error.assert_called_once_with()+ kernel32.WaitForSingleObject.assert_not_called()+ kernel32.CloseHandle.assert_not_called()++ def test_windows_api_failures_are_conservatively_live(self):+ kernel32 = mock.Mock()+ kernel32.OpenProcess.side_effect = OSError("injected API failure")+ with mock.patch.object(+ _cli,+ "_windows_process_api",+ return_value=(kernel32, mock.Mock()),+ ):+ self.assertTrue(_cli._windows_process_is_alive(4567))++ def test_posix_probe_behavior_is_unchanged(self):+ cases = (+ (None, True),+ (ProcessLookupError(), False),+ (PermissionError(), True),+ (OSError(errno.ESRCH, "missing"), False),+ )+ for error, expected in cases:+ with self.subTest(error=type(error).__name__):+ side_effect = error if error is not None else None+ with mock.patch.object(_cli.os, "name", "posix"), \+ mock.patch.object(+ _cli.os, "kill", side_effect=side_effect+ ) as kill:+ self.assertEqual(_cli._process_is_alive(4567), expected)+ kill.assert_called_once_with(4567, 0)+++class RuntimeSetTests(unittest.TestCase):+ def test_candidate_probe_requires_the_binary_to_execute(self):+ candidates = (+ Path("/tmp/codebase-memory-mcp"),+ PureWindowsPath("/tmp/codebase-memory-mcp"),+ )++ for candidate in candidates:+ with self.subTest(candidate=candidate):+ with mock.patch.object(_cli.subprocess, "run") as run:+ run.return_value.returncode = 0+ _cli._verify_candidate(candidate)++ self.assertEqual(+ run.call_args.args[0],+ [str(candidate), "--version"],+ )++ def test_orphan_reconciliation_rejects_multiply_linked_backup_members(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ binary = directory / "codebase-memory-mcp"+ backup = directory / f".cbm-runtime-backup-{'a' * 32}"+ backup.mkdir()+ (backup / ".retirement-complete").write_bytes(b"")+ member = backup / binary.name+ member.write_text("binary:old")+ os.link(member, directory / "backup-hardlink-copy")++ with mock.patch.object(+ _cli, "_bin_path", return_value=binary+ ), self.assertRaisesRegex(+ RuntimeError, "unsafe package-cache backup member"+ ):+ _cli._runtime_set_ready_locked("test-version")++ self.assertTrue(backup.exists(), "unsafe backup was mutated")+ self.assertFalse((directory / _cli._RUNTIME_LOCK_NAME).exists())++ def test_stalled_lock_creator_never_deletes_successor(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ successor = None++ def publish_successor_then_abort():+ nonlocal successor+ _cli._runtime_lock_claim_observer = None+ successor, _ = _cli._acquire_runtime_lock(directory)+ raise RuntimeError("injected stalled creator abort")++ with mock.patch.object(+ _cli,+ "_runtime_lock_claim_observer",+ side_effect=publish_successor_then_abort,+ ), self.assertRaisesRegex(RuntimeError, "stalled creator abort"):+ _cli._acquire_runtime_lock(directory)++ self.assertIsNotNone(successor)+ self.assertTrue(successor[0].exists())+ _cli._release_runtime_lock(successor)++ def test_acquire_closes_claim_descriptor_before_unlink_and_reopens(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ captured = {}+ write_owner = _cli._write_runtime_lock_owner+ unlink = Path.unlink++ def capture_claim_descriptor(owner_fd, token):+ captured["claim_fd"] = owner_fd+ write_owner(owner_fd, token)++ def require_closed_claim_descriptor(path, *args, **kwargs):+ if f"{_cli._RUNTIME_LOCK_NAME}.claim-" in path.name:+ with self.assertRaises(OSError):+ os.fstat(captured["claim_fd"])+ captured["closed_before_unlink"] = True+ return unlink(path, *args, **kwargs)++ with mock.patch.object(+ _cli,+ "_write_runtime_lock_owner",+ side_effect=capture_claim_descriptor,+ ), mock.patch.object(+ Path, "unlink", new=require_closed_claim_descriptor+ ):+ lock, _ = _cli._acquire_runtime_lock(directory)++ try:+ self.assertTrue(captured["closed_before_unlink"])+ self.assertTrue(+ _cli._same_runtime_lock_object(+ os.fstat(lock[2]), lock[0].lstat()+ )+ )+ finally:+ _cli._release_runtime_lock(lock)++ def test_release_closes_descriptor_and_revalidates_each_lock_name(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ lock, _ = _cli._acquire_runtime_lock(directory)+ original_fd = lock[2]+ events = []+ read_owner = _cli._read_runtime_lock_owner+ rename = os.rename++ def record_owner_validation(path):+ events.append(("validate", Path(path).name))+ return read_owner(path)++ def require_closed_descriptor(source, destination):+ with self.assertRaises(OSError):+ os.fstat(original_fd)+ events.append(("rename", Path(source).name))+ return rename(source, destination)++ with mock.patch.object(+ _cli,+ "_read_runtime_lock_owner",+ side_effect=record_owner_validation,+ ), mock.patch.object(+ _cli.os, "rename", side_effect=require_closed_descriptor+ ):+ _cli._release_runtime_lock(lock)++ self.assertEqual(+ events,+ [+ ("validate", _cli._RUNTIME_LOCK_NAME),+ ("validate", _cli._RUNTIME_LOCK_NAME),+ ("rename", _cli._RUNTIME_LOCK_NAME),+ (+ "validate",+ f"{_cli._RUNTIME_LOCK_NAME}.released-{lock[1]}",+ ),+ ],+ )+ self.assertFalse(lock[0].exists())++ def test_release_rejects_owner_substitution_before_rename(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ lock, _ = _cli._acquire_runtime_lock(directory)+ read_owner = _cli._read_runtime_lock_owner+ canonical_reads = 0++ def substitute_owner_on_reopen(path):+ nonlocal canonical_reads+ owner = read_owner(path)+ if Path(path) == lock[0]:+ canonical_reads += 1+ if canonical_reads == 2:+ return (os.getpid(), "f" * 32, owner[2])+ return owner++ with mock.patch.object(+ _cli,+ "_read_runtime_lock_owner",+ side_effect=substitute_owner_on_reopen,+ ):+ with self.assertRaisesRegex(RuntimeError, "ownership changed"):+ _cli._release_runtime_lock(lock)++ self.assertTrue(lock[0].exists())+ lock[0].unlink()++ def test_release_rejects_object_substitution_before_rename(self):+ with tempfile.TemporaryDirectory() as root:+ directory = Path(root)+ lock, _ = _cli._acquire_runtime_lock(directory)+ close = os.close+ substituted = False++ def substitute_object_after_owner_close(owner_fd):+ nonlocal substituted+ if (+ owner_fd != lock[2]+ or substituted+ or not lock[0].exists()+ ):+ close(owner_fd)+ return+ owner_record = lock[0].read_bytes()+ replacement = directory / "replacement-lock"+ replacement.write_bytes(owner_record)+ try:+ close(owner_fd)+ os.replace(replacement, lock[0])+ substituted = True+ finally:+ replacement.unlink(missing_ok=True)++ with mock.patch.object(+ _cli.os,+ "close",+ side_effect=substitute_object_after_owner_close,+ ):+ with self.assertRaisesRegex(RuntimeError, "ownership changed"):+ _cli._release_runtime_lock(lock)++ self.assertTrue(substituted)+ self.assertTrue(lock[0].exists())+ lock[0].unlink()++ def test_expired_lease_never_reclaims_live_owner(self):+ with tempfile.TemporaryDirectory() as root:+ lock_path = Path(root) / _cli._RUNTIME_LOCK_NAME+ owner = {+ "pid": os.getpid(),+ "token": "a" * 32,+ "lease_expires_ms": int((time.time() - 1) * 1000),+ }+ owner_record = f"{json.dumps(owner)}\n"+ lock_path.write_text(owner_record)+ before = lock_path.stat()++ with mock.patch.object(_cli, "_process_is_alive", return_value=True):+ self.assertEqual(+ _cli._try_reclaim_runtime_lock(lock_path, "b" * 32),+ (False, False),+ )+ after = lock_path.stat()+ self.assertEqual(lock_path.read_text(), owner_record)+ self.assertEqual(json.loads(lock_path.read_text())["token"], owner["token"])+ self.assertEqual(after.st_dev, before.st_dev)+ self.assertEqual(after.st_ino, before.st_ino)++ def test_stale_legacy_lock_never_reclaims_live_owner(self):+ with tempfile.TemporaryDirectory() as root:+ lock_path = Path(root) / _cli._RUNTIME_LOCK_NAME+ owner_record = json.dumps(+ {"pid": os.getpid(), "token": "a" * 32}+ ) + "\n"+ lock_path.mkdir()+ (lock_path / "owner.json").write_text(owner_record)+ stale = time.time() - _cli._RUNTIME_LEGACY_STALE_SECONDS - 1+ os.utime(lock_path, (stale, stale))+ before = lock_path.stat()++ with mock.patch.object(_cli, "_process_is_alive", return_value=True):+ self.assertEqual(+ _cli._try_reclaim_runtime_lock(lock_path, "b" * 32),+ (False, False),+ )+ after = lock_path.stat()+ self.assertEqual((lock_path / "owner.json").read_text(), owner_record)+ self.assertEqual(after.st_dev, before.st_dev)+ self.assertEqual(after.st_ino, before.st_ino)++ def test_stale_ownerless_lock_is_reclaimed(self):+ with tempfile.TemporaryDirectory() as root:+ lock_path = Path(root) / _cli._RUNTIME_LOCK_NAME+ lock_path.write_text("")+ stale = time.time() - _cli._RUNTIME_OWNERLESS_STALE_SECONDS - 1+ os.utime(lock_path, (stale, stale))++ self.assertEqual(+ _cli._try_reclaim_runtime_lock(lock_path, "b" * 32),+ (True, False),+ )+ self.assertFalse(lock_path.exists())++ def test_unix_tar_rejects_an_unexpected_root_member(self):+ with tempfile.TemporaryDirectory() as root:+ archive = Path(root) / "release.tar.gz"+ with tarfile.open(archive, "w:gz") as tf:+ for name in (*_cli._UNIX_ARCHIVE_NAMES, "unexpected-root-file"):+ data_path = Path(root) / f"fixture-{len(tf.getmembers())}"+ data_path.write_bytes(name.encode())+ tf.add(data_path, arcname=name)+ destination = Path(root) / "extract"+ destination.mkdir()+ with tarfile.open(archive) as tf, self.assertRaises(SystemExit):+ _cli._safe_extract_tar(+ tf,+ str(destination),+ _cli._UNIX_ARCHIVE_NAMES,+ ("codebase-memory-mcp",),+ )++ def test_unix_tar_rejects_hardlink_members(self):+ with tempfile.TemporaryDirectory() as root:+ archive = Path(root) / "release.tar.gz"+ with tarfile.open(archive, "w:gz") as tf:+ info = tarfile.TarInfo("codebase-memory-mcp")+ info.type = tarfile.LNKTYPE+ info.linkname = "LICENSE"+ tf.addfile(info)+ destination = Path(root) / "extract"+ destination.mkdir()+ with tarfile.open(archive) as tf, self.assertRaises(SystemExit):+ _cli._safe_extract_tar(+ tf,+ str(destination),+ ("codebase-memory-mcp",),+ ("codebase-memory-mcp",),+ False,+ )+ def test_windows_zip_rejects_symlink_metadata(self):+ with tempfile.TemporaryDirectory() as root:+ archive = Path(root) / "release.zip"+ with zipfile.ZipFile(archive, "w") as zf:+ info = zipfile.ZipInfo(_cli._WINDOWS_BINARY_NAME)+ info.create_system = 3+ info.external_attr = (stat.S_IFLNK | 0o777) << 16+ zf.writestr(info, "LICENSE")+ destination = Path(root) / "extract"+ destination.mkdir()+ with zipfile.ZipFile(archive) as zf, self.assertRaises(SystemExit):+ _cli._safe_extract_zip(+ zf,+ str(destination),+ (_cli._WINDOWS_BINARY_NAME,),+ (_cli._WINDOWS_BINARY_NAME,),+ False,+ )-if __name__ == "__main__":- unittest.main()