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

4.5 KB
Raw Blame
import { afterAll, afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test';
import { mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import * as zlib from 'node:zlib';
import { logger } from '../../src/utils/logger.js';
import { TranscriptWatcher } from '../../src/services/transcripts/watcher.js';
import { isZstdSupported } from '../../src/services/transcripts/zstd-frames.js';
import type { TranscriptSchema, WatchTarget } from '../../src/services/transcripts/types.js';

// A transcript that starts with a UTF-8 BOM: JSON.parse throws on U+FEFF, so
// the first line read on its own (a resumed tail's context, a new file's start
// time) must drop it. The tailer itself already trims every record.

const canExerciseZstd = typeof zlib.zstdCompressSync === 'function' && isZstdSupported();
const root = mkdtempSync(join(tmpdir(), 'cm-watcher-bom-'));
afterAll(() => rmSync(root, { recursive: true, force: true }));

const BOM = '';
const schema: TranscriptSchema = { name: 'bom', sessionIdPath: 'session', events: [] };
const firstRecord = { session: 'bom-session', cwd: '/bom-project', timestamp: '2020-01-01T00:00:00.000Z' };
const laterRecord = { session: 'bom-session', text: 'live turn' };

interface Tailer { readTask: Promise<void> | null }
interface WatcherProbe {
  handleLine(line: string): Promise<void>;
  addTailer(path: string, watch: WatchTarget, schema: TranscriptSchema): Promise<void>;
  startedAfterThisWatcher(path: string, isZstd: boolean, size: number): Promise<boolean>;
  tailers: Map<string, Tailer>;
  startedAtMs: number;
  processor: { primeSessionContext(entry: unknown): Promise<void> };
}

let loggerSpies: ReturnType<typeof spyOn>[] = [];
beforeEach(() => {
  loggerSpies = (['info', 'debug', 'warn', 'error'] as const)
    .map(level => spyOn(logger, level).mockImplementation(() => {}));
});
afterEach(() => loggerSpies.forEach(spy => spy.mockRestore()));

/** Resumes a tail past the first record and returns what primed the session context. */
async function resumePastFirstRecord(path: string, contents: Buffer, resumeOffset: number): Promise<unknown[]> {
  writeFileSync(path, contents);
  const statePath = `${path}.state.json`;
  writeFileSync(statePath, JSON.stringify({ offsets: { [path]: resumeOffset } }));
  const watch: WatchTarget = { name: 'bom', path, schema };
  const watcher = new TranscriptWatcher({ version: 1, watches: [watch] }, statePath);
  const probe = watcher as unknown as WatcherProbe;
  const primed: unknown[] = [];
  probe.processor.primeSessionContext = async entry => { primed.push(entry); };
  probe.handleLine = async () => {};
  try {
    await probe.addTailer(path, watch, schema);
    await probe.tailers.get(path)?.readTask;
  } finally {
    watcher.stop();
  }
  return primed;
}

describe('a BOM-prefixed transcript', () => {
  it('primes a resumed JSONL tail from its first record', async () => {
    const path = join(root, 'resumed.jsonl');
    const first = BOM + JSON.stringify(firstRecord) + '\n';
    const contents = Buffer.from(first + JSON.stringify(laterRecord) + '\n');

    const primed = await resumePastFirstRecord(path, contents, Buffer.byteLength(first));

    expect(primed).toEqual([firstRecord]);
  });

  it.skipIf(!canExerciseZstd)('primes a resumed zstd tail from its first record', async () => {
    const path = join(root, 'resumed.jsonl.zstd');
    const firstFrame = zlib.zstdCompressSync(Buffer.from(BOM + JSON.stringify(firstRecord) + '\n'));
    const laterFrame = zlib.zstdCompressSync(Buffer.from(JSON.stringify(laterRecord) + '\n'));

    const primed = await resumePastFirstRecord(path, Buffer.concat([firstFrame, laterFrame]), firstFrame.length);

    expect(primed).toEqual([firstRecord]);
  });

  it('reads the first record time of a copied old transcript', async () => {
    const path = join(root, 'copied.jsonl');
    writeFileSync(path, BOM + JSON.stringify(firstRecord) + '\n' + JSON.stringify(laterRecord) + '\n');
    const watch: WatchTarget = { name: 'bom', path, schema };
    const watcher = new TranscriptWatcher({ version: 1, watches: [watch] }, join(root, 'copied-state.json'));
    const probe = watcher as unknown as WatcherProbe;
    probe.startedAtMs = Date.now(); // set by start(), which would also scan the watch

    // Small enough that the size fallback alone would call it a new session.
    const startedAfter = await probe.startedAfterThisWatcher(path, false, statSync(path).size);
    watcher.stop();

    expect(startedAfter).toBe(false);
  });
});