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

3.9 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { getDefaultWorkerPort } from '../../src/shared/install-port.js';

/**
 * An invalid CLAUDE_MEM_WORKER_PORT end to end through the real worker-service
 * entry point: every command that binds or reaches the port refuses with the
 * validation message, and nothing starts a worker on the derived default port.
 */

const root = join(import.meta.dir, '..', '..');
const workerServiceEntry = join(root, 'src/services/worker-service.ts');
/** WORKER_BOOT_FAILED_EXIT_CODE in src/services/worker-service.ts. */
const WORKER_BOOT_FAILED_EXIT_CODE = 78;
const INVALID_PORT = '37700abc';
const VALIDATION_MESSAGE = `CLAUDE_MEM_WORKER_PORT must be a whole number from 1 to 65535 (got "${INVALID_PORT}")`;

let dataDirectory: string;

function clientEnvironment(): Record<string, string> {
  const { CLAUDE_MEM_WORKER_AUTOSTART: _autostart, CLAUDE_MEM_WORKER_URL: _url, ...inherited } = process.env;
  return {
    ...(inherited as Record<string, string>),
    CLAUDE_MEM_DATA_DIR: dataDirectory,
    CLAUDE_MEM_WORKER_HOST: '127.0.0.1',
    CLAUDE_MEM_WORKER_PORT: INVALID_PORT,
    CLAUDE_MEM_RUNTIME: 'worker',
    CLAUDE_MEM_TELEMETRY: '0',
  };
}

async function runWorkerService(args: string[], stdin = '') {
  const child = Bun.spawn([process.execPath, workerServiceEntry, ...args], {
    cwd: root,
    env: clientEnvironment(),
    stdin: new Blob([stdin]),
    stdout: 'pipe',
    stderr: 'pipe',
  });
  const [stdout, stderr, exitCode] = await Promise.all([
    new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited,
  ]);
  return { stdout, stderr, exitCode };
}

function expectNoLocalWorkerLaunched(): void {
  expect(existsSync(join(dataDirectory, 'worker.pid'))).toBe(false);
}

beforeEach(() => {
  dataDirectory = mkdtempSync(join(tmpdir(), 'claude-mem-worker-port-'));
});

afterEach(() => {
  // Only reached by a regression: stop the local worker it launched.
  const pidFile = join(dataDirectory, 'worker.pid');
  if (existsSync(pidFile)) {
    try { process.kill(JSON.parse(readFileSync(pidFile, 'utf8')).pid, 'SIGKILL'); } catch { /* already gone */ }
  }
  rmSync(dataDirectory, { recursive: true, force: true, maxRetries: 5, retryDelay: 20 });
});

describe('an invalid CLAUDE_MEM_WORKER_PORT', () => {
  it('start reports the validation message as an error status and launches nothing', async () => {
    const { stdout } = await runWorkerService(['start']);
    const status = JSON.parse(stdout.trim().split('\n').pop()!);
    expect(status.status).toBe('error');
    expect(status.message).toContain(VALIDATION_MESSAGE);
    expectNoLocalWorkerLaunched();
  }, 30_000);

  it('a daemon boot fails instead of binding the default install port', async () => {
    const { exitCode } = await runWorkerService(['--daemon']);
    expect(exitCode).toBe(WORKER_BOOT_FAILED_EXIT_CODE);
    expectNoLocalWorkerLaunched();
    const fallback = await fetch(`http://127.0.0.1:${getDefaultWorkerPort(dataDirectory)}/api/health`).catch(() => null);
    expect(fallback).toBeNull();
  }, 30_000);

  it('status exits nonzero with the validation message', async () => {
    const { exitCode, stderr } = await runWorkerService(['status']);
    expect(exitCode).toBe(1);
    expect(stderr).toContain(VALIDATION_MESSAGE);
  }, 30_000);

  it('a hook prints the validation message, exits 0, and launches nothing', async () => {
    const hookInput = JSON.stringify({
      session_id: 'worker-port-invalid', cwd: root, hook_event_name: 'UserPromptSubmit', prompt: 'hello',
    });
    const { exitCode, stderr } = await runWorkerService(['hook', 'claude-code', 'session-init'], hookInput);
    expect(exitCode).toBe(0);
    expect(stderr).toContain(`claude-mem: hook error, continuing without memory: ${VALIDATION_MESSAGE}`);
    expectNoLocalWorkerLaunched();
  }, 30_000);
});