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

8.0 KB
Raw Blame
import { afterAll, beforeEach, mock } from 'bun:test';
import { Database } from 'bun:sqlite';
import { appendFileSync, mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { releaseOnnxRuntimeForExit } from './helpers/onnxruntime-exit-guard.js';

/**
 * Data-dir tripwire (Phase 6, worker-restart plan): no test may ever touch the
 * real ~/.claude-mem. src/shared/paths.ts freezes DATA_DIR at first evaluation
 * (env CLAUDE_MEM_DATA_DIR wins), and module-level consts like ProcessManager's
 * PID_FILE inherit that frozen value — so the env var must point at a safe
 * directory BEFORE any application module loads. The runner preload clears
 * the inherited setting before importing this module. Fixture subprocesses
 * can also preload this module directly with their own data directory.
 * Only the process that creates a temporary directory removes it on exit.
 */
if (!process.env.CLAUDE_MEM_DATA_DIR) {
  const dataDir = mkdtempSync(join(tmpdir(), 'claude-mem-test-run-'));
  process.env.CLAUDE_MEM_DATA_DIR = dataDir;
  process.on('exit', () => {
    try {
      rmSync(dataDir, { recursive: true, force: true });
    } catch (error) {
      console.warn(`Could not remove test data directory ${dataDir}:`, error);
    }
  });
}

// The suite asserts each capture at the call. Production leaves this unset and
// holds the high-volume events for the daily file (src/services/telemetry/daily-volume.ts).
process.env.CLAUDE_MEM_TELEMETRY_IMMEDIATE = '1';

/**
 * Auto-update tripwire: no test may start a real auto-update — a hop, a
 * supervisor, or `npx claude-mem@<version> update` against the real ~/.claude
 * install (CLAUDE_CONFIG_DIR is not isolated here the way the data dir is).
 * While this is set, every production effect that could start one refuses
 * before it acts (FORBID_REAL_AUTO_UPDATE_ENV in
 * src/services/auto-update/auto-update-launch.ts), and every process a test
 * starts inherits it. Set unconditionally, so a shell that exports it empty
 * cannot turn it off. It is not a setting: tests of the shipped defaults see
 * CLAUDE_MEM_AUTO_UPDATE as shipped.
 */
process.env.CLAUDE_MEM_FORBID_REAL_AUTO_UPDATE = '1';

// The cmem cap probe (src/shared/cmem-cap-probe.ts) is a file in the data dir.
// One test's allowance_exhausted must not withhold gateway sends in the next.
// Subprocesses spawned by tests load this preload outside the test runner,
// where beforeEach throws; only the runner needs the hook.
try {
  beforeEach(() => {
    const dataDir = process.env.CLAUDE_MEM_DATA_DIR;
    if (dataDir) rmSync(join(dataDir, 'cmem-cap-probe.json'), { force: true });
  });
} catch {
  // not under `bun test`
}

// A run that loaded the embedding model ended, on macOS, in "panic: A C++
// exception occurred" (Abort trap: 6, exit 134) after every test had passed,
// so the run failed. See tests/helpers/onnxruntime-exit-guard.ts. A preload's
// afterAll runs once, after the last test file. When
// CLAUDE_MEM_ORT_EXIT_GUARD_REPORT names a file, the result is added to it,
// so tests/infrastructure/onnxruntime-exit-guard.test.ts can check this hook.
try {
  afterAll(() => {
    const result = releaseOnnxRuntimeForExit();
    const report = process.env.CLAUDE_MEM_ORT_EXIT_GUARD_REPORT;
    if (report) appendFileSync(report, `guard ${result}\n`);
  });
} catch {
  // not under `bun test`
}

/**
 * Global posthog-node mock, registered via bunfig.toml [test].preload BEFORE
 * any test file or src module loads. It must be global, not per-file:
 *
 *  1. telemetry.ts imports PostHog at module top level, and many src modules
 *     (ResponseProcessor, SessionRoutes, SearchRoutes, worker-service, ...)
 *     transitively import telemetry.ts. The whole suite runs in one bun
 *     process, so a per-file mock.module registers too late once any earlier
 *     test file has touched those modules — the cached telemetry module keeps
 *     the real PostHog binding.
 *  2. Telemetry consent is default-on and the publishable key ships in the
 *     code, so without this mock a full-suite run constructs a REAL PostHog
 *     client and can flush fabricated test events into production analytics
 *     (flushAt: 20 / flushInterval: 10s vs a ~25s suite).
 *
 * Tests assert against these recorded calls — see
 * tests/telemetry/telemetry-client.test.ts.
 */
export type PostHogConstructorCall = { apiKey: string; options: Record<string, unknown> };
export const postHogConstructorCalls: PostHogConstructorCall[] = [];
export const postHogCaptureCalls: Array<Record<string, unknown>> = [];
/**
 * Records captureException(error, distinctId, additionalProperties) calls so
 * Phase 3 error-capture tests can assert on the $exception payload (redacted
 * message/stack, $process_person_profile:false, occurrence_count) without a
 * real client. Mirrors postHogCaptureCalls. Reset per-file like the others.
 */
export type PostHogExceptionCall = {
  error: unknown;
  distinctId?: string;
  additionalProperties?: Record<string | number, unknown>;
};
export const postHogExceptionCalls: PostHogExceptionCall[] = [];

/**
 * Behavior knob for the mock below. When `emitErrorOnShutdown` is set, the
 * next shutdown() call emits it through every handler registered via
 * on('error', ...) before resolving — simulating posthog-node's real
 * delivery-failure surface (shutdown() swallows fetch errors internally; the
 * public error emitter is the only failure signal). Tests that set it MUST
 * reset it to null afterwards.
 */
export const postHogMockBehavior: { emitErrorOnShutdown: unknown | null } = {
  emitErrorOnShutdown: null,
};

mock.module('posthog-node', () => ({
  PostHog: class {
    private handlers: Record<string, Array<(...args: unknown[]) => void>> = {};
    constructor(apiKey: string, options: Record<string, unknown>) {
      postHogConstructorCalls.push({ apiKey, options });
    }
    capture(payload: Record<string, unknown>): void {
      postHogCaptureCalls.push(payload);
    }
    captureException(
      error: unknown,
      distinctId?: string,
      additionalProperties?: Record<string | number, unknown>
    ): void {
      postHogExceptionCalls.push({ error, distinctId, additionalProperties });
    }
    on(event: string, handler: (...args: unknown[]) => void): () => void {
      (this.handlers[event] ??= []).push(handler);
      return () => {};
    }
    /** Test-only trigger mirroring the real SDK's internal emitter. */
    emit(event: string, ...args: unknown[]): void {
      for (const handler of this.handlers[event] ?? []) handler(...args);
    }
    async flush(): Promise<void> {}
    async shutdown(): Promise<void> {
      if (postHogMockBehavior.emitErrorOnShutdown !== null) {
        this.emit('error', postHogMockBehavior.emitErrorOnShutdown);
      }
    }
  },
}));

/**
 * The provider fallback defaults to the Anthropic plan and is used only when a
 * Claude login or key exists (src/shared/claude-fallback-readiness.ts). That
 * check reads the developer's real ~/.claude.json and Claude credentials, so
 * pin it to "no Claude login" for every test: a suite must not pass or fail
 * depending on whether the machine running it is signed in to Claude. Tests
 * that exercise the Claude fallback opt in with setClaudeFallbackReadinessForTesting
 * (imported from the import-free override module so nothing else loads early).
 */
const { setClaudeFallbackReadinessForTesting } = await import('../src/shared/claude-fallback-readiness-override.js');
setClaudeFallbackReadinessForTesting(() => false);

// SQLite 3.37 rejects .get() on RETURNING statements. Catch prepared-variable
// reads too, which the source scanner cannot associate with their SQL.
for (const method of ['prepare', 'query'] as const) {
  const original = Database.prototype[method];
  Database.prototype[method] = function (this: Database, sql: string, ...args: unknown[]) {
    const statement = Reflect.apply(original, this, [sql, ...args]);
    if (/\bRETURNING\b/i.test(sql)) {
      statement.get = () => { throw new Error('Read SQLite RETURNING statements with .all(), not .get()'); };
    }
    return statement;
  } as typeof original;
}