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

12.3 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0

import { describe, it, expect, beforeEach, afterEach, afterAll, mock } from 'bun:test';

// Snapshot the real module BEFORE mock.module mutates the live namespace, then
// re-register it in afterAll. bun's mock.module is process-global and
// mock.restore() does NOT undo it, so this partial worker-utils stub would
// otherwise leak into other test files in the same `bun test` run.
import * as realWorkerUtils from '../../src/shared/worker-utils.js';
const realWorkerUtilsSnapshot = { ...realWorkerUtils };
let capturedTimeouts: number[] = [];

mock.module('../../src/shared/worker-utils.js', () => ({
  fetchWithTimeout: async (url: string, init: RequestInit, timeoutMs: number) => {
    capturedTimeouts.push(timeoutMs);
    return globalThis.fetch(url, init);
  },
}));

afterAll(() => {
  mock.module('../../src/shared/worker-utils.js', () => realWorkerUtilsSnapshot);
});

import {
  ServerClient,
  ServerClientError,
  isServerClientError,
} from '../../src/services/hooks/server-client.js';

interface CapturedRequest {
  url: string;
  method: string;
  headers: Record<string, string>;
  body?: unknown;
}

let captured: CapturedRequest[] = [];
const originalFetch = globalThis.fetch;

function installFetch(handler: (req: CapturedRequest) => Response | Promise<Response>): void {
  // Reset capture buffer for each test.
  captured = [];
  globalThis.fetch = (async (url: string, init: RequestInit = {}) => {
    const headers: Record<string, string> = {};
    const rawHeaders = init.headers ?? {};
    if (Array.isArray(rawHeaders)) {
      for (const [k, v] of rawHeaders) headers[k.toLowerCase()] = v;
    } else {
      for (const [k, v] of Object.entries(rawHeaders as Record<string, string>)) {
        headers[k.toLowerCase()] = v;
      }
    }
    const body = init.body ? JSON.parse(String(init.body)) : undefined;
    const req: CapturedRequest = { url, method: String(init.method ?? 'GET'), headers, body };
    captured.push(req);
    return handler(req);
  }) as typeof globalThis.fetch;
}

describe('ServerClient', () => {
  beforeEach(() => {
    captured = [];
    capturedTimeouts = [];
  });

  afterEach(() => {
    globalThis.fetch = originalFetch;
  });

  it('throws missing_api_key when apiKey is empty', async () => {
    const client = new ServerClient({ serverBaseUrl: 'http://x', apiKey: '' });
    let caught: unknown;
    try {
      await client.recordEvent({
        projectId: 'p1',
        sourceType: 'hook',
        eventType: 'tool_use',
        occurredAtEpoch: 1,
      });
    } catch (error) {
      caught = error;
    }
    expect(isServerClientError(caught)).toBe(true);
    if (caught instanceof ServerClientError) {
      expect(caught.kind).toBe('missing_api_key');
      expect(caught.isFallbackEligible()).toBe(true);
    }
  });

  it('startSession sends POST /v1/sessions/start with expected payload', async () => {
    installFetch(async () => new Response(JSON.stringify({ session: { id: 'sess-1', projectId: 'p1', teamId: 't1', externalSessionId: 'ext', contentSessionId: 'ext' } }), { status: 201, headers: { 'content-type': 'application/json' } }));
    const client = new ServerClient({ serverBaseUrl: 'http://localhost:9999/', apiKey: 'cmem_test' });
    const result = await client.startSession({
      projectId: 'p1',
      externalSessionId: 'ext',
      contentSessionId: 'ext',
      platformSource: 'claude-code',
    });
    expect(captured).toHaveLength(1);
    expect(captured[0]?.url).toBe('http://localhost:9999/v1/sessions/start');
    expect(captured[0]?.method).toBe('POST');
    expect(captured[0]?.headers.authorization).toBe('Bearer cmem_test');
    expect(captured[0]?.headers['content-type']).toBe('application/json');
    expect((captured[0]?.body as Record<string, unknown>).projectId).toBe('p1');
    expect((captured[0]?.body as Record<string, unknown>).externalSessionId).toBe('ext');
    expect((captured[0]?.body as Record<string, unknown>).platformSource).toBe('claude');
    expect(result.session.id).toBe('sess-1');
  });

  it('recordEvent sends POST /v1/events with payload', async () => {
    installFetch(async () => new Response(JSON.stringify({ event: { id: 'e1', projectId: 'p1', serverSessionId: null } }), { status: 201 }));
    const client = new ServerClient({ serverBaseUrl: 'http://localhost:9999', apiKey: 'cmem_test' });
    const result = await client.recordEvent({
      projectId: 'p1',
      contentSessionId: 'cs1',
      platformSource: 'Codex CLI',
      sourceType: 'hook',
      eventType: 'tool_use',
      occurredAtEpoch: 1234,
      payload: { tool: 'Read' },
    });
    expect(captured[0]?.url).toBe('http://localhost:9999/v1/events');
    expect((captured[0]?.body as Record<string, unknown>).eventType).toBe('tool_use');
    expect((captured[0]?.body as Record<string, unknown>).sourceType).toBe('hook');
    expect((captured[0]?.body as Record<string, unknown>).occurredAtEpoch).toBe(1234);
    expect((captured[0]?.body as Record<string, unknown>).platformSource).toBe('codex');
    expect(result.event.id).toBe('e1');
  });

  it('recordEvent forwards a per-request timeout override', async () => {
    installFetch(async () => new Response(JSON.stringify({
      event: { id: 'e-timeout', projectId: 'p1', serverSessionId: null },
    }), { status: 201 }));
    const client = new ServerClient({
      serverBaseUrl: 'http://localhost:9999',
      apiKey: 'cmem_test',
      timeoutMs: 30_000,
    });

    await client.recordEvent({
      projectId: 'p1',
      sourceType: 'hook',
      eventType: 'tool_use',
      occurredAtEpoch: 1,
    }, { timeoutMs: 2_000 });

    expect(capturedTimeouts).toEqual([2_000]);
  });

  it('endSession sends POST /v1/sessions/:id/end', async () => {
    installFetch(async () => new Response(JSON.stringify({ session: { id: 'sess-1' } }), { status: 200 }));
    const client = new ServerClient({ serverBaseUrl: 'http://localhost:9999', apiKey: 'cmem_test' });
    await client.endSession({ sessionId: 'sess-1' });
    expect(captured[0]?.url).toBe('http://localhost:9999/v1/sessions/sess-1/end');
    expect(captured[0]?.method).toBe('POST');
  });

  it('throws transport error on fetch failure', async () => {
    globalThis.fetch = (async () => {
      throw new Error('ECONNREFUSED');
    }) as typeof globalThis.fetch;
    const client = new ServerClient({ serverBaseUrl: 'http://localhost:9999', apiKey: 'cmem_test' });
    let caught: unknown;
    try {
      await client.recordEvent({ projectId: 'p1', sourceType: 'hook', eventType: 'tool_use', occurredAtEpoch: 1 });
    } catch (error) {
      caught = error;
    }
    expect(isServerClientError(caught)).toBe(true);
    if (caught instanceof ServerClientError) {
      expect(caught.kind).toBe('transport');
      expect(caught.isFallbackEligible()).toBe(true);
    }
  });

  it.each([[502, true], [400, false], [429, true]] as const)('classifies HTTP %i with fallback eligibility %s', async (status, fallbackEligible) => {
    installFetch(async () => new Response('error', { status }));
    const client = new ServerClient({ serverBaseUrl: 'http://localhost:9999', apiKey: 'cmem_test' });
    let caught: unknown;
    try {
      await client.recordEvent({ projectId: 'p1', sourceType: 'hook', eventType: 'tool_use', occurredAtEpoch: 1 });
    } catch (error) {
      caught = error;
    }
    expect(caught).toBeInstanceOf(ServerClientError);
    if (caught instanceof ServerClientError) {
      expect(caught.kind).toBe('http_error');
      expect(caught.status).toBe(status);
      expect(caught.isFallbackEligible()).toBe(fallbackEligible);
    }
  });

  it('strips trailing slash from baseUrl', async () => {
    installFetch(async () => new Response(JSON.stringify({ session: { id: 's' } }), { status: 200 }));
    const client = new ServerClient({ serverBaseUrl: 'http://localhost:9999///', apiKey: 'cmem_test' });
    await client.endSession({ sessionId: 's' });
    expect(captured[0]?.url).toBe('http://localhost:9999/v1/sessions/s/end');
  });

  it('contextObservations sends POST /v1/context and returns context string', async () => {
    installFetch(async () => new Response(
      JSON.stringify({
        observations: [{ id: 'o1', projectId: 'p1', content: 'a' }, { id: 'o2', projectId: 'p1', content: 'b' }],
        context: 'a\n\nb',
      }),
      { status: 200 },
    ));
    const client = new ServerClient({ serverBaseUrl: 'http://localhost:9999', apiKey: 'cmem_test' });
    const result = await client.contextObservations({ projectId: 'p1', query: 'q', platformSource: 'Cursor' });
    expect(captured[0]?.url).toBe('http://localhost:9999/v1/context');
    expect((captured[0]?.body as Record<string, unknown>).platformSource).toBe('cursor');
    expect(result.context).toBe('a\n\nb');
    expect(result.observations).toHaveLength(2);
  });

  it('getJobStatus rejects empty jobId', async () => {
    const client = new ServerClient({ serverBaseUrl: 'http://x', apiKey: 'cmem_test' });
    let caught: unknown;
    try {
      await client.getJobStatus('');
    } catch (error) {
      caught = error;
    }
    expect(caught).toBeInstanceOf(ServerClientError);
  });

  it('payload builders omit absent fields', () => {
    const client = new ServerClient({ serverBaseUrl: 'http://x', apiKey: 'k' });
    // `content` goes over the wire AS `content`. This assertion previously
    // required `narrative` + `type`, which is CreateMemoryItemSchema — the
    // contract of ServerV1Routes, the SQLite /v1/memories that worker-service
    // mounts. This client is only ever built on the `server` runtime, so the
    // route it actually reaches is ServerV1PostgresRoutes, which validates
    // `content: z.string().min(1)`. The old payload returned 400
    // ValidationError "path":["content"] on every MCP observation_add, and
    // tests/server/runtime/server-mcp-routes.test.ts reproduces it 4-red
    // against a real Postgres.
    expect(client.buildAddObservationPayload({ projectId: 'p', content: 'c' })).toEqual({
      projectId: 'p',
      kind: 'manual',
      content: 'c',
    });
    expect(client.buildSearchPayload({ projectId: 'p', query: 'q' })).toEqual({
      projectId: 'p',
      query: 'q',
    });
    expect(client.buildSearchPayload({ projectId: 'p', query: 'q', limit: 7 })).toEqual({
      projectId: 'p',
      query: 'q',
      limit: 7,
    });
    expect(client.buildSearchPayload({ projectId: 'p', query: 'q', platformSource: 'Codex CLI' })).toEqual({
      projectId: 'p',
      query: 'q',
      platformSource: 'codex',
    });
    expect(client.buildEventPayload({
      projectId: 'p',
      sourceType: 'hook',
      eventType: 'tool_use',
      occurredAtEpoch: 1,
      platformSource: 'Claude Code',
    })).toEqual({
      projectId: 'p',
      sourceType: 'hook',
      eventType: 'tool_use',
      occurredAtEpoch: 1,
      platformSource: 'claude',
    });
    expect(client.buildStartSessionPayload({
      projectId: 'p',
      externalSessionId: 'ext',
      platformSource: 'Cursor',
    })).toEqual({
      projectId: 'p',
      externalSessionId: 'ext',
      platformSource: 'cursor',
    });
  });

  it('strips <private> sections from every server-bound event payload and session metadata', () => {
    const client = new ServerClient({ serverBaseUrl: 'http://x', apiKey: 'k' });
    const eventBody = client.buildEventPayload({
      projectId: 'p',
      sourceType: 'hook',
      eventType: 'tool_use',
      occurredAtEpoch: 1,
      payload: {
        tool_name: 'Bash',
        tool_input: { command: 'echo hi <private>secret-token-123</private>' },
        tool_response: { stdout: ['line', '<private>secret-output</private>'] },
        last_assistant_message: 'done <private>secret-reply</private>',
        untouched: '  keeps whitespace  ',
      },
    });
    const serialized = JSON.stringify(eventBody);
    expect(serialized).not.toContain('secret-token-123');
    expect(serialized).not.toContain('secret-output');
    expect(serialized).not.toContain('secret-reply');
    expect((eventBody.payload as Record<string, unknown>).untouched).toBe('  keeps whitespace  ');
    expect((eventBody.payload as Record<string, any>).tool_input.command).toBe('echo hi');

    const sessionBody = client.buildStartSessionPayload({
      projectId: 'p',
      externalSessionId: 'ext',
      metadata: { project: 'demo', prompt: 'fix the bug <private>my password is hunter2</private>' },
    });
    expect(JSON.stringify(sessionBody)).not.toContain('hunter2');
    expect(sessionBody.metadata).toEqual({ project: 'demo', prompt: 'fix the bug' });
  });
});