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

40.4 KB
Raw Blame
import { describe, it, expect, afterEach } from 'bun:test';
import { mkdtempSync, mkdirSync, rmSync, existsSync, writeFileSync, symlinkSync, readFileSync } from 'fs';
import { tmpdir } from 'os';
import path, { join } from 'path';
import { spawnSync } from 'node:child_process';
import {
  planCachePrune,
  planPluginCachePrune,
  prunePluginCache,
  pruneSupersededPluginCache,
  readRegisteredCacheVersions,
  readUserScopeRegisteredCacheVersions,
  workingCacheVersions,
  isDirectChildPath,
  hostInUseCacheVersions,
  hostProcessVerdict,
  isClaudeProcessName,
  isHostProcessLive,
  readHostInUseRecords,
  evaluateHostInUseRecords,
  describePrunedVersion,
  describeProcessNameOverride,
  DEFAULT_CACHE_RETENTION,
  type HostProcessProbe,
} from '../../src/npx-cli/utils/prune-cache.js';

/**
 * A cache version directory as the installer leaves it: the plugin files with
 * a worker script and a package.json declaring one dependency. `complete`
 * installs that dependency; a fresh copy has none until "Setting up runtime".
 */
function writeCacheVersion(root: string, version: string, complete: boolean): void {
  const versionDir = join(root, version);
  mkdirSync(join(versionDir, 'scripts'), { recursive: true });
  writeFileSync(join(versionDir, 'scripts', 'worker-service.cjs'), '');
  writeFileSync(join(versionDir, 'package.json'), JSON.stringify({ version, dependencies: { 'left-pad': '1.3.0' } }));
  if (complete) {
    mkdirSync(join(versionDir, 'node_modules', 'left-pad'), { recursive: true });
    writeFileSync(join(versionDir, 'node_modules', 'left-pad', 'package.json'), '{"name":"left-pad"}');
  }
}

describe('planCachePrune', () => {
  it('keeps the newest two versions by default and prunes the rest', () => {
    const { keep, prune } = planCachePrune(
      ['13.24.0', '13.25.0', '13.25.1', '13.20.0'],
      DEFAULT_CACHE_RETENTION,
    );
    expect(keep).toEqual(['13.25.1', '13.25.0']);
    expect(prune).toEqual(['13.24.0', '13.20.0']);
  });

  it('ignores names that are not version directories', () => {
    const { keep, prune } = planCachePrune(
      ['13.25.1', '13.25.0', '13.24.0', '.tmp', 'node_modules'],
      2,
    );
    expect(keep).not.toContain('.tmp');
    expect(prune).not.toContain('.tmp');
    expect(prune).toContain('13.24.0');
  });

  it('ranks release ahead of prerelease at the same base', () => {
    const { keep } = planCachePrune(
      ['13.25.1', '13.25.1-beta.1', '13.24.0'],
      2,
    );
    expect(keep).toEqual(['13.25.1', '13.25.1-beta.1']);
  });

  it('prunes nothing when the version count is within the keep budget', () => {
    const { prune } = planCachePrune(['13.25.1', '13.25.0'], 2);
    expect(prune).toEqual([]);
  });
});

describe('prunePluginCacheSafely protects the running worker', () => {
  it.each([
    ['old live version', { version: '13.20.0' }, false, false, []],
    ['missing version', {}, false, true, []],
    ['invalid version', { version: 123 }, false, true, []],
    ['invalid JSON', 'invalid-json', false, true, []],
    ['health timeout', 'timeout', false, true, []],
    ['silent port with owned worker', 'refused', true, true, []],
    ['no worker', 'refused', false, false, ['13.20.0']],
  ])('%s', (_name, health, owned, retainAll, removed) => {
    const root = mkdtempSync(join(tmpdir(), 'claude-mem-prune-live-'));
    try {
      for (const version of ['13.20.0', '13.24.0', '13.25.0']) mkdirSync(join(root, version));
      const script = `
        import { mock } from 'bun:test';
        const paths = await import(${JSON.stringify(join(import.meta.dir, '../../src/npx-cli/utils/paths.ts'))});
        const registry = await import(${JSON.stringify(join(import.meta.dir, '../../src/supervisor/process-registry.ts'))});
        mock.module(${JSON.stringify(join(import.meta.dir, '../../src/npx-cli/utils/paths.ts'))}, () => ({
          ...paths, installedPluginsPath: () => ${JSON.stringify(join(root, 'missing-registry.json'))},
        }));
        mock.module(${JSON.stringify(join(import.meta.dir, '../../src/supervisor/process-registry.ts'))}, () => ({
          ...registry, readOwnedWorkerPidInfo: () => ${owned ? '{ pid: 123 }' : 'null'},
        }));
        const health = ${JSON.stringify(health)};
        let requests = 0;
        globalThis.fetch = async (url) => {
          if (!String(url).endsWith('/api/health')) throw new Error('unexpected URL: ' + url);
          requests++;
          if (health === 'timeout') throw new Error('request timed out');
          if (health === 'refused') throw new Error('ECONNREFUSED');
          return new Response(health === 'invalid-json' ? '{' : JSON.stringify(health));
        };
        const { prunePluginCacheSafely } = await import(${JSON.stringify(join(import.meta.dir, '../../src/npx-cli/utils/prune-cache.ts'))});
        const result = await prunePluginCacheSafely({ cacheRoot: ${JSON.stringify(root)}, keepCount: 2 });
        console.log(JSON.stringify({ result, requests }));
      `;
      const child = spawnSync(process.execPath, ['--eval', script], {
        env: { ...process.env, CLAUDE_MEM_DATA_DIR: join(root, 'data'), CLAUDE_CONFIG_DIR: join(root, 'claude') },
        encoding: 'utf8', timeout: 10_000,
      });
      expect(child.status, child.stderr).toBe(0);
      const { result, requests } = JSON.parse(child.stdout.trim().split('\n').at(-1)!);
      expect(requests).toBe(1);
      expect(result.retainedForLiveWorker).toBe(retainAll);
      expect(result.removed).toEqual(removed);
      expect(result.failed).toEqual([]);
      for (const version of ['13.20.0', '13.24.0', '13.25.0']) {
        expect(existsSync(join(root, version))).toBe(!removed.includes(version));
      }
    } finally {
      rmSync(root, { recursive: true, force: true });
    }
  });
});

describe('prunePluginCache', () => {
  let root: string;

  afterEach(() => {
    if (root && existsSync(root)) rmSync(root, { recursive: true, force: true });
  });

  it('removes superseded version directories on disk and keeps the newest', () => {
    root = mkdtempSync(join(tmpdir(), 'claude-mem-prune-'));
    for (const version of ['13.20.0', '13.24.0', '13.25.0', '13.25.1']) {
      mkdirSync(join(root, version));
    }

    const result = prunePluginCache({ cacheRoot: root, keepCount: 2 });

    expect(result.removed.sort()).toEqual(['13.20.0', '13.24.0']);
    expect(existsSync(join(root, '13.25.1'))).toBe(true);
    expect(existsSync(join(root, '13.25.0'))).toBe(true);
    expect(existsSync(join(root, '13.24.0'))).toBe(false);
    expect(existsSync(join(root, '13.20.0'))).toBe(false);
  });

  it('returns an empty result when the cache root does not exist', () => {
    root = join(tmpdir(), 'claude-mem-prune-missing-does-not-exist');
    const result = prunePluginCache({ cacheRoot: root, keepCount: 2 });
    expect(result.removed).toEqual([]);
    expect(result.kept).toEqual([]);
  });

  it('prunes an orphaned newest directory and keeps usable rollback versions', () => {
    root = mkdtempSync(join(tmpdir(), 'claude-mem-prune-orphan-'));
    for (const version of ['13.24.0', '13.25.0', '13.26.0']) {
      mkdirSync(join(root, version));
    }
    // Claude Code stamps the superseded newest directory as orphaned.
    writeFileSync(join(root, '13.26.0', '.orphaned_at'), '');

    const result = prunePluginCache({ cacheRoot: root, keepCount: 2 });

    expect(result.removed).toEqual(['13.26.0']);
    expect(existsSync(join(root, '13.26.0'))).toBe(false);
    expect(existsSync(join(root, '13.25.0'))).toBe(true);
    expect(existsSync(join(root, '13.24.0'))).toBe(true);
  });
});

describe('prunePluginCache — never deletes the install that can still start a worker', () => {
  let root: string;
  const originalOverride = process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH;

  afterEach(() => {
    if (originalOverride === undefined) delete process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH;
    else process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH = originalOverride;
    if (root && existsSync(root)) rmSync(root, { recursive: true, force: true });
  });

  it('keeps the only dependency-complete version while the newer copies still lack dependencies', () => {
    // The installer prunes right after copying 13.26.0 and before "Setting up
    // runtime" installs its dependencies; 13.25.0 is a failed earlier install.
    // Keeping just the newest two deleted 13.24.0, the only copy that could run.
    root = mkdtempSync(join(tmpdir(), 'claude-mem-prune-working-'));
    writeCacheVersion(root, '13.26.0', false);
    writeCacheVersion(root, '13.25.0', false);
    writeCacheVersion(root, '13.24.0', true);
    writeCacheVersion(root, '13.23.0', true);

    const result = prunePluginCache({ cacheRoot: root, keepCount: 2 });

    expect(result.removed).toEqual(['13.23.0']);
    expect(existsSync(join(root, '13.24.0', 'scripts', 'worker-service.cjs'))).toBe(true);
  });

  it('keeps the version the worker resolver picks, even outside the newest two', () => {
    root = mkdtempSync(join(tmpdir(), 'claude-mem-prune-resolved-'));
    for (const version of ['13.20.0', '13.24.0', '13.25.0', '13.25.1']) writeCacheVersion(root, version, true);
    // resolveWorkerScript() honors this override first: every launcher spawns it.
    process.env.CLAUDE_MEM_WORKER_SCRIPT_PATH = join(root, '13.20.0', 'scripts', 'worker-service.cjs');

    const result = prunePluginCache({ cacheRoot: root, keepCount: 2 });

    expect(result.removed).toEqual(['13.24.0']);
    expect(existsSync(join(root, '13.20.0'))).toBe(true);
  });

  it('protects nothing extra for a resolver pick outside the cache', () => {
    root = mkdtempSync(join(tmpdir(), 'claude-mem-prune-outside-'));
    writeCacheVersion(root, '13.25.0', false);
    const outside = { scriptPath: join(tmpdir(), 'elsewhere', '13.20.0', 'scripts', 'worker-service.cjs'), version: '13.20.0' };
    // No cache copy is complete, so the newest installed one stands in.
    expect(workingCacheVersions(root, outside)).toEqual(['13.25.0']);
  });
});

describe('planPluginCachePrune', () => {
  let root: string;

  afterEach(() => {
    if (root && existsSync(root)) rmSync(root, { recursive: true, force: true });
  });

  it('reads .orphaned_at markers from disk and previews the same removals', () => {
    root = mkdtempSync(join(tmpdir(), 'claude-mem-prune-plan-'));
    for (const version of ['13.24.0', '13.25.0', '13.26.0']) {
      mkdirSync(join(root, version));
    }
    writeFileSync(join(root, '13.26.0', '.orphaned_at'), '');

    const { keep, prune } = planPluginCachePrune(root, 2);
    expect(prune).toEqual(['13.26.0']);
    expect(keep).toEqual(['13.25.0', '13.24.0']);
    // Preview only — nothing deleted.
    expect(existsSync(join(root, '13.26.0'))).toBe(true);
  });
});

describe('readRegisteredCacheVersions', () => {
  let root: string;

  afterEach(() => {
    if (root && existsSync(root)) rmSync(root, { recursive: true, force: true });
  });

  function writeRegistry(contents: string): string {
    root = mkdtempSync(join(tmpdir(), 'claude-mem-prune-registry-'));
    const registryPath = join(root, 'installed_plugins.json');
    writeFileSync(registryPath, contents);
    return registryPath;
  }

  it('returns the cache directory names claude-mem is registered at', () => {
    const registryPath = writeRegistry(JSON.stringify({
      version: 2,
      plugins: {
        'claude-mem@thedotmack': [{ scope: 'user', installPath: '/home/u/.claude/plugins/cache/thedotmack/claude-mem/13.20.0', version: '13.20.0' }],
        'other@someone': [{ installPath: '/home/u/.claude/plugins/cache/someone/other/9.9.9' }],
      },
    }));
    expect(readRegisteredCacheVersions(registryPath)).toEqual(['13.20.0']);
  });

  it('returns nothing when the registry is missing or has no claude-mem entry', () => {
    expect(readRegisteredCacheVersions(join(tmpdir(), 'claude-mem-no-such-registry.json'))).toEqual([]);
    expect(readRegisteredCacheVersions(writeRegistry(JSON.stringify({ version: 2, plugins: {} })))).toEqual([]);
  });

  it('throws on a corrupt registry so nothing is pruned blind', () => {
    const registryPath = writeRegistry('{ not json');
    expect(() => readRegisteredCacheVersions(registryPath)).toThrow(/Corrupt JSON/);
  });

  it('protects every scope\'s registered version, while the auto-updater reads only the user-scope entry the npx installer writes', () => {
    // Project-local scratch (gitignored), never the system temp folder.
    const scratchRoot = join(import.meta.dir, '..', '..', '.scratch', 'test-runs');
    mkdirSync(scratchRoot, { recursive: true });
    const scratch = mkdtempSync(join(scratchRoot, 'prune-registry-scopes-'));
    try {
      const registryPath = join(scratch, 'installed_plugins.json');
      const entry = (scope: string, version: string) => ({ scope, installPath: join(scratch, 'cache', version), version, ...(scope === 'user' ? {} : { projectPath: '/work/p' }) });
      writeFileSync(registryPath, JSON.stringify({ version: 2, plugins: { 'claude-mem@thedotmack': [entry('project', '13.19.0'), entry('user', '13.20.0'), entry('local', '13.18.0')] } }));
      expect(readRegisteredCacheVersions(registryPath)).toEqual(['13.19.0', '13.20.0', '13.18.0']);
      expect(readUserScopeRegisteredCacheVersions(registryPath)).toEqual(['13.20.0']);

      writeFileSync(registryPath, JSON.stringify({ version: 2, plugins: { 'claude-mem@thedotmack': [entry('project', '13.19.0')] } }));
      expect(readUserScopeRegisteredCacheVersions(registryPath)).toEqual([]);

      writeFileSync(registryPath, '{ not json');
      expect(() => readUserScopeRegisteredCacheVersions(registryPath)).toThrow(/Corrupt JSON/);
    } finally {
      rmSync(scratch, { recursive: true, force: true });
    }
  });

  it('keeps a downgraded registered install that is older than the newest two', () => {
    // Downgrade with the worker stopped: Claude Code loads 13.20.0, which is
    // outside the newest-2 budget. Deleting it would break the registered install.
    const registryPath = writeRegistry(JSON.stringify({
      plugins: { 'claude-mem@thedotmack': [{ installPath: join(root, 'cache', '13.20.0') }] },
    }));
    const cacheRoot = join(root, 'cache');
    for (const version of ['13.20.0', '13.24.0', '13.25.0', '13.25.1']) {
      mkdirSync(join(cacheRoot, version), { recursive: true });
    }

    const result = prunePluginCache({
      cacheRoot,
      keepCount: 2,
      protectedVersions: readRegisteredCacheVersions(registryPath),
    });

    expect(result.removed).toEqual(['13.24.0']);
    expect(existsSync(join(cacheRoot, '13.20.0'))).toBe(true);
  });
});

describe('isDirectChildPath', () => {
  it('accepts one version segment on Windows and POSIX paths and rejects an escape', () => {
    const winRoot = 'C:\\Users\\Ada\\.claude\\plugins\\cache\\thedotmack\\claude-mem';
    expect(isDirectChildPath(winRoot, `${winRoot}\\15.15.1`, path.win32)).toBe(true);
    expect(isDirectChildPath(winRoot, 'C:\\Users\\Ada\\.claude\\plugins\\cache\\someone\\other\\15.15.1', path.win32)).toBe(false);
    expect(isDirectChildPath(winRoot, 'C:\\Windows\\System32', path.win32)).toBe(false);

    const posixRoot = '/home/ada/.claude/plugins/cache/thedotmack/claude-mem';
    expect(isDirectChildPath(posixRoot, `${posixRoot}/15.15.1`, path.posix)).toBe(true);
    expect(isDirectChildPath(posixRoot, '/home/ada/.claude/plugins/cache/someone/other', path.posix)).toBe(false);
    expect(isDirectChildPath(posixRoot, `${posixRoot}/15.15.1/scripts`, path.posix)).toBe(false);
  });
});

function writeWorkerScript(root: string, version: string): string {
  const script = join(root, version, 'scripts', 'worker-service.cjs');
  mkdirSync(join(root, version, 'scripts'), { recursive: true });
  writeFileSync(script, '');
  return script;
}

describe('pruneSupersededPluginCache', () => {
  let scratch: string;

  afterEach(() => {
    if (scratch && existsSync(scratch)) rmSync(scratch, { recursive: true, force: true });
  });

  it('keeps the running version and the newest two, and leaves everything else outside the cache', async () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem prune '));
    const root = join(scratch, 'cache');
    const running = writeWorkerScript(root, '15.5.0');
    writeWorkerScript(root, '15.14.0');
    writeWorkerScript(root, '15.15.0');
    writeWorkerScript(root, '15.15.1');
    mkdirSync(join(root, 'notes'));
    writeFileSync(join(root, 'notes', 'keep.txt'), 'notes');
    const neighbor = join(scratch, 'other-plugin', '15.0.0');
    mkdirSync(neighbor, { recursive: true });
    writeFileSync(join(neighbor, 'keep.txt'), 'neighbor');

    const result = await pruneSupersededPluginCache({
      cacheRoot: root,
      keepCount: 2,
      runningScriptPath: running,
      registryPath: join(scratch, 'no-registry.json'),
    });

    expect(result.removed).toEqual(['15.14.0']);
    expect(existsSync(join(root, '15.5.0', 'scripts', 'worker-service.cjs'))).toBe(true);
    expect(existsSync(join(root, '15.15.1'))).toBe(true);
    expect(existsSync(join(root, '15.15.0'))).toBe(true);
    expect(existsSync(join(root, '15.14.0'))).toBe(false);
    expect(readFileSync(join(root, 'notes', 'keep.txt'), 'utf-8')).toBe('notes');
    expect(readFileSync(join(neighbor, 'keep.txt'), 'utf-8')).toBe('neighbor');
  });

  it('never removes the folder the worker runs from when that version is a symlink out of the cache', async () => {
    // Running from the link's target: the script is outside the cache root, so only the
    // resolved-path check stands between the sweep and the live worker's own folder.
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-running-link-'));
    const root = join(scratch, 'cache');
    const elsewhere = join(scratch, 'dev-checkout');
    const running = writeWorkerScript(elsewhere, '15.4.0');
    mkdirSync(root);
    symlinkSync(join(elsewhere, '15.4.0'), join(root, '15.4.0'));
    writeWorkerScript(root, '15.15.0');
    writeWorkerScript(root, '15.15.1');

    const result = await pruneSupersededPluginCache({
      cacheRoot: root,
      keepCount: 2,
      runningScriptPath: join(elsewhere, '15.4.0', 'scripts'),
      registryPath: join(scratch, 'no-registry.json'),
    });

    expect(result.removed).toEqual([]);
    expect(result.failed.map(failure => failure.version)).toEqual(['15.4.0']);
    expect(existsSync(join(root, '15.4.0', 'scripts', 'worker-service.cjs'))).toBe(true);
    expect(existsSync(running)).toBe(true);
  });

  it("keeps the worker's own package version even when it is older than the newest two", async () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-package-version-'));
    const root = join(scratch, 'cache');
    for (const version of ['15.5.0', '15.14.0', '15.15.0', '15.15.1']) writeWorkerScript(root, version);

    const result = await pruneSupersededPluginCache({
      cacheRoot: root,
      keepCount: 2,
      additionalProtectedVersions: ['15.5.0'],
      registryPath: join(scratch, 'no-registry.json'),
    });

    expect(result.removed).toEqual(['15.14.0']);
    expect(existsSync(join(root, '15.5.0', 'scripts', 'worker-service.cjs'))).toBe(true);
  });

  it('removes an old version when nothing is running from it', async () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-unprotected-'));
    const root = join(scratch, 'cache');
    for (const version of ['15.5.0', '15.15.0', '15.15.1']) writeWorkerScript(root, version);

    const result = await pruneSupersededPluginCache({
      cacheRoot: root,
      keepCount: 2,
      registryPath: join(scratch, 'no-registry.json'),
    });

    expect(result.removed).toEqual(['15.5.0']);
    expect(existsSync(join(root, '15.5.0'))).toBe(false);
  });

  it('does not follow a symlink version or a symlink inside a removed version', async () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-symlink-'));
    const root = join(scratch, 'cache');
    const preciousDir = join(scratch, 'precious');
    mkdirSync(preciousDir);
    writeFileSync(join(preciousDir, 'keep.txt'), 'keep');
    mkdirSync(root);
    symlinkSync(preciousDir, join(root, '15.4.0'));
    const inside = join(root, '15.4.1');
    mkdirSync(inside);
    const preciousFile = join(scratch, 'precious.txt');
    writeFileSync(preciousFile, 'file');
    symlinkSync(preciousFile, join(inside, 'link'));
    writeWorkerScript(root, '15.15.0');
    writeWorkerScript(root, '15.15.1');

    const result = await pruneSupersededPluginCache({
      cacheRoot: root,
      keepCount: 2,
      registryPath: join(scratch, 'no-registry.json'),
    });

    expect(result.removed.sort()).toEqual(['15.4.0', '15.4.1']);
    expect(readFileSync(join(preciousDir, 'keep.txt'), 'utf-8')).toBe('keep');
    expect(readFileSync(preciousFile, 'utf-8')).toBe('file');
    expect(existsSync(join(root, '15.15.1'))).toBe(true);
  });

  it('returns an empty removal when the cache root does not exist', async () => {
    scratch = join(tmpdir(), 'claude-mem-prune-absent-root');
    const result = await pruneSupersededPluginCache({
      cacheRoot: join(scratch, 'missing'),
      registryPath: join(scratch, 'no-registry.json'),
    });
    expect(result.removed).toEqual([]);
    expect(result.kept).toEqual([]);
  });

  it('throws on a corrupt registry before deleting anything', async () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-corrupt-'));
    const root = join(scratch, 'cache');
    writeWorkerScript(root, '15.5.0');
    writeWorkerScript(root, '15.15.0');
    writeWorkerScript(root, '15.15.1');
    const registryPath = join(scratch, 'installed_plugins.json');
    writeFileSync(registryPath, '{ not json');

    await expect(pruneSupersededPluginCache({ cacheRoot: root, registryPath })).rejects.toThrow(/Corrupt JSON/);
    expect(existsSync(join(root, '15.5.0'))).toBe(true);
  });

  it('keeps the version installed_plugins.json registers even when it is older than the newest two', async () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-registered-'));
    const root = join(scratch, 'cache');
    for (const version of ['15.5.0', '15.14.0', '15.15.0', '15.15.1']) writeWorkerScript(root, version);
    const registryPath = join(scratch, 'installed_plugins.json');
    writeFileSync(registryPath, JSON.stringify({
      plugins: { 'claude-mem@thedotmack': [{ scope: 'user', installPath: join(root, '15.5.0') }] },
    }));

    const result = await pruneSupersededPluginCache({ cacheRoot: root, keepCount: 2, registryPath });

    expect(result.removed).toEqual(['15.14.0']);
    expect(existsSync(join(root, '15.5.0'))).toBe(true);
  });
});

/** Claude Code's record that process `pid` loaded the plugin from this version folder. */
function writeHostInUseRecord(root: string, version: string, pid: number, content: string = JSON.stringify({ pid })): void {
  mkdirSync(join(root, version, '.in_use'), { recursive: true });
  writeFileSync(join(root, version, '.in_use', String(pid)), content);
}

/** PID of a process that has already exited. */
function exitedPid(): number {
  return spawnSync(process.execPath, ['-e', '']).pid;
}

describe('a version a running host session is loaded from (#5970)', () => {
  let scratch: string;

  afterEach(() => {
    if (scratch && existsSync(scratch)) rmSync(scratch, { recursive: true, force: true });
  });

  it('the worker sweep keeps an orphaned version while a recorded process is alive, and removes it once that process has exited', async () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-in-use-'));
    const root = join(scratch, 'cache');
    const running = writeWorkerScript(root, '15.16.1');
    // A marketplace update stamps the folders it supersedes. One session is
    // still open on 15.15.2; the session that used 15.15.1 has ended.
    for (const version of ['15.15.1', '15.15.2']) {
      writeWorkerScript(root, version);
      writeFileSync(join(root, version, '.orphaned_at'), '');
    }
    writeHostInUseRecord(root, '15.15.2', process.pid);
    const ended = exitedPid();
    writeHostInUseRecord(root, '15.15.1', ended);
    const sweep = () => pruneSupersededPluginCache({
      cacheRoot: root,
      keepCount: 2,
      runningScriptPath: running,
      registryPath: join(scratch, 'no-registry.json'),
    });

    const first = await sweep();

    expect(first.removed).toEqual(['15.15.1']);
    expect(first.kept).toContain('15.15.2');
    expect(existsSync(join(root, '15.15.2', 'scripts', 'worker-service.cjs'))).toBe(true);

    rmSync(join(root, '15.15.2', '.in_use', String(process.pid)));
    writeHostInUseRecord(root, '15.15.2', ended);
    const second = await sweep();

    expect(second.removed).toEqual(['15.15.2']);
    expect(existsSync(join(root, '15.15.2'))).toBe(false);
  });

  it('the installer prune and its preview keep it too', () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-in-use-installer-'));
    for (const version of ['13.24.0', '13.25.0', '13.26.0', '13.27.0']) mkdirSync(join(scratch, version));
    writeHostInUseRecord(scratch, '13.24.0', process.pid);

    const plan = planPluginCachePrune(scratch, 2);
    expect(plan.keep).toEqual(['13.27.0', '13.26.0', '13.24.0']);
    expect(plan.prune).toEqual(['13.25.0']);

    const result = prunePluginCache({ cacheRoot: scratch, keepCount: 2 });

    expect(result.removed).toEqual(['13.25.0']);
    expect(existsSync(join(scratch, '13.24.0'))).toBe(true);
  });

  it('a record that names no live process protects nothing', () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-in-use-stale-'));
    for (const version of ['13.24.0', '13.26.0', '13.27.0']) mkdirSync(join(scratch, version));
    mkdirSync(join(scratch, '13.24.0', '.in_use'));
    writeFileSync(join(scratch, '13.24.0', '.in_use', 'notes.txt'), 'not a record');
    writeHostInUseRecord(scratch, '13.24.0', exitedPid(), '');

    const result = prunePluginCache({ cacheRoot: scratch, keepCount: 2 });

    expect(result.removed).toEqual(['13.24.0']);
  });

  it('a record that cannot be parsed still protects the live process its file name names', () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-in-use-blank-'));
    for (const version of ['13.24.0', '13.26.0', '13.27.0']) mkdirSync(join(scratch, version));
    writeHostInUseRecord(scratch, '13.24.0', process.pid, '{ truncated');

    expect(readHostInUseRecords(join(scratch, '13.24.0'))).toEqual([{ pid: process.pid }]);
    expect(prunePluginCache({ cacheRoot: scratch, keepCount: 2 }).removed).toEqual([]);
  });

  it('reads each recorded process once per sweep, however many versions record it', () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-in-use-once-'));
    const recordedStart = 'Wed Nov 11 06:05:51 2026';
    const versions = ['13.24.0', '13.25.0', '13.26.0'];
    for (const version of versions) {
      mkdirSync(join(scratch, version));
      writeHostInUseRecord(scratch, version, 4242, JSON.stringify({ pid: 4242, procStart: recordedStart }));
    }
    const reads = { alive: 0, startToken: 0 };
    const probe: HostProcessProbe = {
      isAlive: () => { reads.alive += 1; return true; },
      startToken: () => { reads.startToken += 1; return `utc:${recordedStart}`; },
    };

    expect(hostInUseCacheVersions(scratch, versions, probe)).toEqual(versions);
    expect(reads).toEqual({ alive: 1, startToken: 1 });
  });
});

describe('isHostProcessLive', () => {
  const recordedStart = 'Wed Nov 11 06:05:51 2026';
  function probe(alive: boolean, token: string | null): HostProcessProbe & { tokenReads: number } {
    const calls = { tokenReads: 0 };
    return Object.assign(calls, {
      isAlive: () => alive,
      startToken: () => { calls.tokenReads += 1; return token; },
    });
  }

  it('is false for a process that has exited, without reading a start time', () => {
    const dead = probe(false, `utc:${recordedStart}`);
    expect(isHostProcessLive({ pid: 4242, procStart: recordedStart }, dead)).toBe(false);
    expect(dead.tokenReads).toBe(0);
  });

  it('is true for a live process whose start time matches the record', () => {
    expect(isHostProcessLive({ pid: 4242, procStart: recordedStart }, probe(true, `utc:${recordedStart}`))).toBe(true);
  });

  it('is false when the PID now belongs to a process that started at another time', () => {
    expect(isHostProcessLive({ pid: 4242, procStart: recordedStart }, probe(true, 'utc:Thu Nov 12 09:41:07 2026'))).toBe(false);
  });

  it('keeps a live PID when the start times cannot be compared', () => {
    // Linux reads a numeric /proc start time, and an unreadable token is no proof.
    expect(isHostProcessLive({ pid: 4242, procStart: recordedStart }, probe(true, '8123456'))).toBe(true);
    expect(isHostProcessLive({ pid: 4242, procStart: recordedStart }, probe(true, null))).toBe(true);
    // A record without a start time, or with one in another shape, is not read at all.
    const unread = probe(true, 'utc:Thu Nov 12 09:41:07 2026');
    expect(isHostProcessLive({ pid: 4242 }, unread)).toBe(true);
    expect(isHostProcessLive({ pid: 4242, procStart: '2026-11-11T06:05:51Z' }, unread)).toBe(true);
    expect(unread.tokenReads).toBe(0);
  });
});

describe('a live Claude process whose recorded start time does not match (#6349)', () => {
  const recordedStart = 'Tue Nov 17 17:51:04 2026';
  // The reading the worker's UTC-pinned `ps` probe returns for a process that
  // started a day after the recorded one: an unambiguous PID-reuse reading.
  const reusedToken = 'utc:Wed Nov 18 17:51:04 2026';

  function namedProbe(name: string | null): HostProcessProbe & { nameReads: number } {
    const calls = { nameReads: 0 };
    return Object.assign(calls, {
      isAlive: () => true,
      startToken: () => reusedToken,
      name: () => { calls.nameReads += 1; return name; },
    });
  }

  it('keeps the folder while the recorded PID is a live Claude process, whatever the start-time verdict', () => {
    expect(isHostProcessLive({ pid: 4242, procStart: recordedStart }, namedProbe('claude'))).toBe(true);
    expect(isHostProcessLive({ pid: 4242, procStart: recordedStart }, namedProbe('claude helper'))).toBe(true);
    expect(isHostProcessLive({ pid: 4242, procStart: recordedStart }, namedProbe('claude-code'))).toBe(true);
  });

  it('still prunes when the PID now belongs to another program', () => {
    expect(hostProcessVerdict({ pid: 4242, procStart: recordedStart }, namedProbe('node')))
      .toEqual({ live: false, reason: 'start-time-mismatch' });
    expect(hostProcessVerdict({ pid: 4242, procStart: recordedStart }, namedProbe('claude-mem')))
      .toEqual({ live: false, reason: 'start-time-mismatch' });
  });

  it('keeps the old verdict when the process name cannot be read', () => {
    expect(isHostProcessLive({ pid: 4242, procStart: recordedStart }, namedProbe(null))).toBe(false);
    const noName: HostProcessProbe = { isAlive: () => true, startToken: () => reusedToken };
    expect(isHostProcessLive({ pid: 4242, procStart: recordedStart }, noName)).toBe(false);
  });

  it('never reads a name for a process that has exited', () => {
    const probe = namedProbe('claude');
    const dead: HostProcessProbe = { ...probe, isAlive: () => false };
    expect(hostProcessVerdict({ pid: 4242, procStart: recordedStart }, dead))
      .toEqual({ live: false, reason: 'process-exited' });
    expect(probe.nameReads).toBe(0);
  });

  it('protects the version in a full sweep plan while its Claude process lives', () => {
    const scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-6349-plan-'));
    for (const version of ['15.19.0', '16.0.0', '16.0.1']) mkdirSync(join(scratch, version));
    writeFileSync(join(scratch, '15.19.0', '.orphaned_at'), String(Date.now()));
    writeHostInUseRecord(scratch, '15.19.0', 4242, JSON.stringify({ pid: 4242, procStart: recordedStart }));

    expect(hostInUseCacheVersions(scratch, ['15.19.0', '16.0.0', '16.0.1'], namedProbe('claude')))
      .toEqual(['15.19.0']);
    expect(hostInUseCacheVersions(scratch, ['15.19.0', '16.0.0', '16.0.1'], namedProbe('node')))
      .toEqual([]);
    rmSync(scratch, { recursive: true, force: true });
  });

  it('recognizes Claude process names and rejects lookalikes', () => {
    expect(isClaudeProcessName('claude')).toBe(true);
    expect(isClaudeProcessName('claude helper')).toBe(true);
    expect(isClaudeProcessName('claude-code')).toBe(true);
    expect(isClaudeProcessName('claude-mem')).toBe(false);
    expect(isClaudeProcessName('claudette')).toBe(false);
    expect(isClaudeProcessName('node')).toBe(false);
    expect(isClaudeProcessName(null)).toBe(false);
  });
});

describe('prune diagnostics (#6349)', () => {
  let scratch: string | undefined;
  afterEach(() => {
    if (scratch) rmSync(scratch, { recursive: true, force: true });
    scratch = undefined;
  });

  it('reports why each version was pruned and which .in_use records were rejected', () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-6349-diagnostics-'));
    for (const version of ['13.24.0', '13.25.0', '13.26.0', '13.27.0']) writeCacheVersion(scratch, version, true);
    writeFileSync(join(scratch, '13.24.0', '.orphaned_at'), String(Date.now()));
    const dead = exitedPid();
    writeHostInUseRecord(scratch, '13.24.0', dead, JSON.stringify({ pid: dead, procStart: 'Wed Nov 11 06:05:51 2026' }));

    const result = prunePluginCache({ cacheRoot: scratch, keepCount: 2 });

    expect(result.removed).toEqual(expect.arrayContaining(['13.24.0', '13.25.0']));
    expect(result.pruneReasons?.['13.24.0']).toBe('orphaned');
    expect(result.pruneReasons?.['13.25.0']).toBe('superseded');
    expect(result.rejectedHostRecords).toEqual([
      { version: '13.24.0', pid: dead, procStart: 'Wed Nov 11 06:05:51 2026', reason: 'process-exited' },
    ]);
  });

  it('lists rejected records with their reasons, and none for a record that keeps its version', () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-6349-rejections-'));
    for (const version of ['13.24.0', '13.25.0']) mkdirSync(join(scratch, version));
    const dead = exitedPid();
    writeHostInUseRecord(scratch, '13.24.0', dead, JSON.stringify({ pid: dead, procStart: 'Wed Nov 11 06:05:51 2026' }));
    writeHostInUseRecord(scratch, '13.25.0', 4242, JSON.stringify({ pid: 4242, procStart: 'Wed Nov 11 06:05:51 2026' }));
    const probe: HostProcessProbe = {
      isAlive: pid => pid === 4242,
      startToken: () => 'utc:Thu Nov 12 09:41:07 2026',
      name: () => 'node',
    };

    expect(evaluateHostInUseRecords(scratch, ['13.24.0', '13.25.0'], probe).rejectedRecords).toEqual([
      { version: '13.24.0', pid: dead, procStart: 'Wed Nov 11 06:05:51 2026', reason: 'process-exited' },
      { version: '13.25.0', pid: 4242, procStart: 'Wed Nov 11 06:05:51 2026', reason: 'start-time-mismatch' },
    ]);
    const claudeProbe: HostProcessProbe = { ...probe, name: () => 'claude' };
    expect(evaluateHostInUseRecords(scratch, ['13.25.0'], claudeProbe).rejectedRecords).toEqual([]);
  });

  it('reports the verdict the plan used, reading each process once (Greptile P2 on #6352)', () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-6349-one-pass-'));
    for (const version of ['13.24.0', '13.26.0', '13.27.0']) mkdirSync(join(scratch, version));
    writeHostInUseRecord(scratch, '13.24.0', 4242, JSON.stringify({ pid: 4242, procStart: 'Wed Nov 11 06:05:51 2026' }));
    // The process is alive at the first read and gone at any later one. A
    // second diagnostic pass would report process-exited, though the plan
    // pruned on a start-time mismatch.
    const reads = { alive: 0, startToken: 0, name: 0 };
    const probe: HostProcessProbe = {
      isAlive: () => { reads.alive += 1; return reads.alive === 1; },
      startToken: () => { reads.startToken += 1; return 'utc:Thu Nov 12 09:41:07 2026'; },
      name: () => { reads.name += 1; return 'node'; },
    };

    const plan = planPluginCachePrune(scratch, 2, [], probe);

    expect(plan.prune).toEqual(['13.24.0']);
    expect(plan.pruneReasons).toEqual({ '13.24.0': 'superseded' });
    expect(plan.rejectedHostRecords).toEqual([
      { version: '13.24.0', pid: 4242, procStart: 'Wed Nov 11 06:05:51 2026', reason: 'start-time-mismatch' },
    ]);
    expect(reads).toEqual({ alive: 1, startToken: 1, name: 1 });
  });

  it('names a version kept only because the process-name check beat a start-time mismatch', () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-6349-override-'));
    for (const version of ['15.18.0', '15.19.0', '16.0.0', '16.0.1']) mkdirSync(join(scratch, version));
    writeFileSync(join(scratch, '15.19.0', '.orphaned_at'), String(Date.now()));
    const recordedStart = 'Tue Nov 17 17:51:04 2026';
    // 15.19.0: only the override keeps it. 15.18.0: a matching record keeps it
    // as well. 16.0.1: retention keeps it anyway.
    writeHostInUseRecord(scratch, '15.19.0', 4242, JSON.stringify({ pid: 4242, procStart: recordedStart }));
    writeHostInUseRecord(scratch, '15.18.0', 4242, JSON.stringify({ pid: 4242, procStart: recordedStart }));
    writeHostInUseRecord(scratch, '15.18.0', 5151, JSON.stringify({ pid: 5151, procStart: recordedStart }));
    writeHostInUseRecord(scratch, '16.0.1', 4242, JSON.stringify({ pid: 4242, procStart: recordedStart }));
    const probe: HostProcessProbe = {
      isAlive: () => true,
      startToken: pid => (pid === 5151 ? `utc:${recordedStart}` : 'utc:Wed Nov 18 17:51:04 2026'),
      name: () => 'claude',
    };

    const plan = planPluginCachePrune(scratch, 2, [], probe);

    expect(plan.prune).toEqual([]);
    expect(plan.keptByProcessNameOverride).toEqual([{
      version: '15.19.0',
      pid: 4242,
      procStart: recordedStart,
      currentStartToken: 'utc:Wed Nov 18 17:51:04 2026',
      processName: 'claude',
    }]);
    expect(describeProcessNameOverride(plan.keptByProcessNameOverride[0])).toBe(
      'Kept 15.19.0: pid 4242 is still a Claude process (claude), though its start time '
      + 'utc:Wed Nov 18 17:51:04 2026 differs from the .in_use record (Tue Nov 17 17:51:04 2026)',
    );
  });

  it('describes each pruned version with its reason and rejected records', () => {
    const evidence = {
      pruneReasons: { '13.24.0': 'orphaned', '13.25.0': 'superseded' } as const,
      rejectedHostRecords: [
        { version: '13.24.0', pid: 11, reason: 'process-exited' as const },
        { version: '13.24.0', pid: 12, procStart: 'Wed Nov 11 06:05:51 2026', reason: 'start-time-mismatch' as const },
      ],
    };
    expect(describePrunedVersion('13.24.0', evidence))
      .toBe('13.24.0 (orphaned; .in_use pid 11 process-exited; .in_use pid 12 start-time-mismatch)');
    expect(describePrunedVersion('13.25.0', evidence)).toBe('13.25.0 (superseded)');
    expect(() => describePrunedVersion('13.26.0', evidence)).toThrow(/No prune reason/);
  });

  it('npx claude-mem prune prints the reason for each version it removes or would remove', () => {
    scratch = mkdtempSync(join(tmpdir(), 'claude-mem-prune-6349-command-'));
    const root = join(scratch, 'cache');
    for (const version of ['13.20.0', '13.24.0', '13.25.0', '13.26.0']) mkdirSync(join(root, version), { recursive: true });
    writeFileSync(join(root, '13.20.0', '.orphaned_at'), String(Date.now()));
    const dead = exitedPid();
    writeHostInUseRecord(root, '13.20.0', dead);
    const run = (args: string[]): string => {
      const script = `
        import { mock } from 'bun:test';
        const paths = await import(${JSON.stringify(join(import.meta.dir, '../../src/npx-cli/utils/paths.ts'))});
        const registry = await import(${JSON.stringify(join(import.meta.dir, '../../src/supervisor/process-registry.ts'))});
        mock.module(${JSON.stringify(join(import.meta.dir, '../../src/npx-cli/utils/paths.ts'))}, () => ({
          ...paths,
          pluginCacheRootDirectory: () => ${JSON.stringify(root)},
          installedPluginsPath: () => ${JSON.stringify(join(scratch!, 'missing-registry.json'))},
        }));
        mock.module(${JSON.stringify(join(import.meta.dir, '../../src/supervisor/process-registry.ts'))}, () => ({
          ...registry, readOwnedWorkerPidInfo: () => null,
        }));
        globalThis.fetch = async () => { throw new Error('ECONNREFUSED'); };
        const { runPruneCommand } = await import(${JSON.stringify(join(import.meta.dir, '../../src/npx-cli/commands/prune.ts'))});
        await runPruneCommand(${JSON.stringify(args)});
      `;
      const child = spawnSync(process.execPath, ['--eval', script], {
        env: { ...process.env, CLAUDE_MEM_DATA_DIR: join(scratch!, 'data'), CLAUDE_CONFIG_DIR: join(scratch!, 'claude'), NO_COLOR: '1' },
        encoding: 'utf8', timeout: 10_000,
      });
      expect(child.status, child.stderr).toBe(0);
      return child.stdout.replace(/\u001b\[[0-9;]*m/g, '');
    };

    const preview = run(['--dry-run']);
    expect(preview).toContain(`Would remove: 13.24.0 (superseded), 13.20.0 (orphaned; .in_use pid ${dead} process-exited)`);
    expect(existsSync(join(root, '13.20.0'))).toBe(true);

    const removal = run([]);
    expect(removal).toContain(`Removed:   13.24.0 (superseded), 13.20.0 (orphaned; .in_use pid ${dead} process-exited)`);
    expect(existsSync(join(root, '13.20.0'))).toBe(false);
  });
});