Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

7.4 KB
Raw Blame
import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { disableClaudeAutoMemory } from '../src/npx-cli/commands/install.js';
import { USER_SETTINGS_PATH } from '../src/shared/paths.js';
import { ownsClaudeAutoMemoryOverride } from '../src/npx-cli/utils/claude-auto-memory.js';

/**
 * Tests for auto-memory disable behavior in the install command.
 *
 * Closes anthropics/claude-code#23544 from claude-mem's side: installs now
 * require explicit consent before setting CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 in
 * ~/.claude/settings.json `env` block. The built-in MEMORY.md system creates
 * shadow state outside the user's control and competes with claude-mem's
 * hook-based memory for context-window tokens, but we should not disable it
 * without the user's opt-in.
 */

const installSourcePath = join(
  __dirname,
  '..',
  'src',
  'npx-cli',
  'commands',
  'install.ts',
);
const installSource = readFileSync(installSourcePath, 'utf-8');

describe('Install: disable Claude Code auto-memory', () => {
  it('resolves non-prompting consent choices in a non-interactive process', () => {
    const script = `
      import { mock } from 'bun:test';
      Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true });
      mock.module('@clack/prompts', () => ({ select: () => { throw new Error('Unexpected consent prompt'); } }));
      const { resolveClaudeAutoMemoryChoice } = await import(${JSON.stringify(installSourcePath)});
      const cases = [[['cursor'], {}], [['claude-code'], { disableAutoMemory: true }], [['claude-code'], {}]];
      const results = [];
      for (const [ides, options] of cases) results.push(await resolveClaudeAutoMemoryChoice(ides, options));
      console.log(JSON.stringify(results));
    `;
    const home = mkdtempSync(join(tmpdir(), 'auto-memory-consent-'));
    try {
      const child = Bun.spawnSync([process.execPath, '-e', script], {
        stdout: 'pipe', stderr: 'pipe', timeout: 10_000,
        env: { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: home, CLAUDE_MEM_DATA_DIR: home },
      });
      expect(child.exitCode).toBe(0);
      expect(JSON.parse(child.stdout.toString().trim())).toEqual(['not-applicable', 'disable', 'leave-enabled']);
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });

  describe('disableClaudeAutoMemory runtime behavior', () => {
    let tempDir: string;
    let originalConfigDir: string | undefined;

    beforeEach(() => {
      tempDir = mkdtempSync(join(tmpdir(), 'claude-mem-disable-auto-memory-'));
      originalConfigDir = process.env.CLAUDE_CONFIG_DIR;
      process.env.CLAUDE_CONFIG_DIR = tempDir;
    });

    afterEach(() => {
      if (originalConfigDir === undefined) {
        delete process.env.CLAUDE_CONFIG_DIR;
      } else {
        process.env.CLAUDE_CONFIG_DIR = originalConfigDir;
      }
      rmSync(tempDir, { recursive: true, force: true });
      rmSync(USER_SETTINGS_PATH, { force: true });
    });

    it('issue #6710: records ownership only when it writes the env var', () => {
      expect(disableClaudeAutoMemory()).toBe(true);
      expect(ownsClaudeAutoMemoryOverride()).toBe(true);
    });

    it('issue #6710: records no ownership for a value the user already set', () => {
      writeFileSync(
        join(tempDir, 'settings.json'),
        JSON.stringify({ env: { CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1' } }),
      );
      expect(disableClaudeAutoMemory()).toBe(false);
      expect(ownsClaudeAutoMemoryOverride()).toBe(false);
    });

    // chmod does not block writes on Windows or for root.
    it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)(
      'issue #6710: forgets the ownership record when the settings write fails',
      () => {
        // settings.json reads fine, but its read-only directory refuses the
        // atomic write's temp file.
        writeFileSync(join(tempDir, 'settings.json'), JSON.stringify({ env: { AWS_REGION: 'us-east-1' } }));
        chmodSync(tempDir, 0o555);
        try {
          expect(() => disableClaudeAutoMemory()).toThrow();
        } finally {
          chmodSync(tempDir, 0o755);
        }
        // A record left behind would let a later uninstall remove a "1" the
        // user sets by hand.
        expect(ownsClaudeAutoMemoryOverride()).toBe(false);
      },
    );

    it('writes the env var when settings.json is missing', () => {
      const wrote = disableClaudeAutoMemory();
      expect(wrote).toBe(true);

      const settings = JSON.parse(readFileSync(join(tempDir, 'settings.json'), 'utf-8'));
      expect(settings.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY).toBe('1');
    });

    it('preserves existing env vars and other top-level keys', () => {
      writeFileSync(
        join(tempDir, 'settings.json'),
        JSON.stringify({
          theme: 'dark',
          env: {
            ANTHROPIC_AUTH_TOKEN: 'sk-test',
            AWS_REGION: 'us-east-1',
          },
          permissions: { defaultMode: 'auto' },
        }, null, 2),
      );

      const wrote = disableClaudeAutoMemory();
      expect(wrote).toBe(true);

      const settings = JSON.parse(readFileSync(join(tempDir, 'settings.json'), 'utf-8'));
      expect(settings.theme).toBe('dark');
      expect(settings.permissions).toEqual({ defaultMode: 'auto' });
      expect(settings.env.ANTHROPIC_AUTH_TOKEN).toBe('sk-test');
      expect(settings.env.AWS_REGION).toBe('us-east-1');
      expect(settings.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY).toBe('1');
    });

    it('is idempotent — second call returns false and leaves the file untouched', () => {
      const firstWrite = disableClaudeAutoMemory();
      expect(firstWrite).toBe(true);

      const settingsPath = join(tempDir, 'settings.json');
      const contentBefore = readFileSync(settingsPath, 'utf-8');

      const secondWrite = disableClaudeAutoMemory();
      expect(secondWrite).toBe(false);

      const contentAfter = readFileSync(settingsPath, 'utf-8');
      expect(contentAfter).toBe(contentBefore);
    });

    it('replaces a non-object env value with a fresh env block', () => {
      writeFileSync(
        join(tempDir, 'settings.json'),
        JSON.stringify({ env: 'not-an-object', theme: 'dark' }),
      );

      const wrote = disableClaudeAutoMemory();
      expect(wrote).toBe(true);

      const settings = JSON.parse(readFileSync(join(tempDir, 'settings.json'), 'utf-8'));
      expect(settings.theme).toBe('dark');
      expect(typeof settings.env).toBe('object');
      expect(settings.env.CLAUDE_CODE_DISABLE_AUTO_MEMORY).toBe('1');
    });
  });
});

// Hook launcher placement (plan-17 #3605, Phase 3). Behavior is covered in
// tests/launcher/install-launcher.test.ts; these pin the installer wiring.
describe('Install: claude-mem hook launcher placement', () => {
  it('places the launcher in the runtime-setup task, after ensureBun and from the cached plugin', () => {
    const runtimeTaskStart = installSource.indexOf("title: 'Setting up runtime (first install can take ~30s)'");
    const ensureBunCall = installSource.indexOf('await ensureBun(summary)', runtimeTaskStart);
    const launcherCall = installSource.indexOf('placeHookLauncherOnPath(cacheDir, summary)', runtimeTaskStart);
    expect(runtimeTaskStart).toBeGreaterThan(-1);
    expect(ensureBunCall).toBeGreaterThan(runtimeTaskStart);
    expect(launcherCall).toBeGreaterThan(ensureBunCall);
  });
});