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

10.3 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import type { TranscriptSchema, WatchTarget } from '../../src/services/transcripts/types.js';
import { logger } from '../../src/utils/logger.js';
import { loadWatchState } from '../../src/services/transcripts/state.js';
import { TranscriptWatcher } from '../../src/services/transcripts/watcher.js';

const contextSchema: TranscriptSchema = {
  name: 'context',
  sessionIdPath: 'session',
  events: [{
    name: 'context',
    action: 'session_context',
    fields: { sessionId: { value: 's' }, cwd: 'cwd' },
  }],
};

const contextLine = (cwd: string) => JSON.stringify({ cwd }) + '\n';

async function waitFor(predicate: () => boolean, timeoutMs = 3000): Promise<void> {
  const deadline = Date.now() + timeoutMs;
  while (!predicate()) {
    if (Date.now() > deadline) throw new Error('timed out waiting for transcript watcher');
    await new Promise(resolve => setTimeout(resolve, 10));
  }
}

describe('TranscriptWatcher handleRootWatchEvent lookup and targeted discovery', () => {
  let tmpRoot: string;
  let loggerSpies: ReturnType<typeof spyOn>[] = [];
  const watchers: TranscriptWatcher[] = [];

  beforeEach(() => {
    tmpRoot = mkdtempSync(join(tmpdir(), 'cm-root-watch-event-'));
    loggerSpies = [
      spyOn(logger, 'info').mockImplementation(() => {}),
      spyOn(logger, 'debug').mockImplementation(() => {}),
      spyOn(logger, 'warn').mockImplementation(() => {}),
      spyOn(logger, 'error').mockImplementation(() => {}),
    ];
  });

  afterEach(() => {
    for (const watcher of watchers.splice(0)) watcher.stop();
    loggerSpies.forEach(spy => spy.mockRestore());
    rmSync(tmpRoot, { recursive: true, force: true });
  });

  it('pokes an existing tailed file registered via start() without rescanning the watch root', async () => {
    const sessionsDir = join(tmpRoot, 'sessions');
    const sessionDir = join(sessionsDir, 'ws-a', 'session-1');
    mkdirSync(sessionDir, { recursive: true });
    const filePath = join(sessionDir, 'session.jsonl');
    writeFileSync(filePath, contextLine('/ws-a'));
    const statePath = join(tmpRoot, 'state.json');

    const watch: WatchTarget = { name: 'dsh', path: sessionsDir, schema: contextSchema };
    const watcher = new TranscriptWatcher({ version: 1, watches: [watch] }, statePath, 'in-process', 0);
    watchers.push(watcher);
    await watcher.start();

    const internal = watcher as any;
    expect(internal.tailers.has(filePath)).toBe(true);
    const tailer = internal.tailers.get(filePath);
    const pokeSpy = spyOn(tailer, 'poke');
    const scanSpy = spyOn(internal, 'resolveWatchFiles');

    internal.handleRootWatchEvent(sessionsDir, sessionsDir, watch, contextSchema, join('ws-a', 'session-1', 'session.jsonl'));

    expect(pokeSpy).toHaveBeenCalledTimes(1);
    expect(scanSpy).not.toHaveBeenCalled();
  });

  it('retires a deleted tailed file registered via start() without rescanning', async () => {
    const sessionsDir = join(tmpRoot, 'sessions');
    const sessionDir = join(sessionsDir, 'ws-a', 'session-1');
    mkdirSync(sessionDir, { recursive: true });
    const filePath = join(sessionDir, 'session.jsonl');
    writeFileSync(filePath, contextLine('/ws-a'));
    const statePath = join(tmpRoot, 'state.json');

    const watch: WatchTarget = { name: 'dsh', path: sessionsDir, schema: contextSchema };
    const watcher = new TranscriptWatcher({ version: 1, watches: [watch] }, statePath, 'in-process', 0);
    watchers.push(watcher);
    await watcher.start();

    const internal = watcher as any;
    const scanSpy = spyOn(internal, 'resolveWatchFiles');
    unlinkSync(filePath);

    internal.handleRootWatchEvent(sessionsDir, sessionsDir, watch, contextSchema, join('ws-a', 'session-1', 'session.jsonl'));

    expect(internal.tailers.has(filePath)).toBe(false);
    expect(scanSpy).not.toHaveBeenCalled();
  });

  it('pokes an existing tailed file under a glob watch without rescanning', async () => {
    const sessionsDir = join(tmpRoot, 'codex');
    const dayDir = join(sessionsDir, '2026', '11');
    mkdirSync(dayDir, { recursive: true });
    const filePath = join(dayDir, 'rollout-1.jsonl');
    writeFileSync(filePath, contextLine('/codex'));
    const statePath = join(tmpRoot, 'state.json');

    const pattern = join(sessionsDir, '**', '*.jsonl');
    const watch: WatchTarget = { name: 'codex', path: pattern, schema: contextSchema };
    const watcher = new TranscriptWatcher({ version: 1, watches: [watch] }, statePath, 'in-process', 0);
    watchers.push(watcher);
    await watcher.start();

    const internal = watcher as any;
    expect(internal.tailers.has(filePath)).toBe(true);
    const pokeSpy = spyOn(internal.tailers.get(filePath), 'poke');
    const scanSpy = spyOn(internal, 'resolveWatchFiles');

    internal.handleRootWatchEvent(sessionsDir, pattern, watch, contextSchema, join('2026', '11', 'rollout-1.jsonl'));

    expect(pokeSpy).toHaveBeenCalledTimes(1);
    expect(scanSpy).not.toHaveBeenCalled();
  });

  it('adds a new transcript file under a directory watch directly without scanning the whole tree', async () => {
    const sessionsDir = join(tmpRoot, 'sessions');
    mkdirSync(join(sessionsDir, 'ws-a', 'session-1'), { recursive: true });
    writeFileSync(join(sessionsDir, 'ws-a', 'session-1', 'session.jsonl'), contextLine('/ws-a'));
    const statePath = join(tmpRoot, 'state.json');

    const watch: WatchTarget = { name: 'dsh', path: sessionsDir, schema: contextSchema };
    const watcher = new TranscriptWatcher({ version: 1, watches: [watch] }, statePath, 'in-process', 0);
    watchers.push(watcher);
    await watcher.start();

    const internal = watcher as any;
    // Silence live OS watches so only our explicit handleRootWatchEvent drives discovery.
    for (const rw of internal.rootWatchers.splice(0)) rw.close();
    const scanSpy = spyOn(internal, 'resolveWatchFiles');

    const newDir = join(sessionsDir, 'ws-a', 'session-2');
    mkdirSync(newDir, { recursive: true });
    const newFile = join(newDir, 'session.jsonl');
    writeFileSync(newFile, contextLine('/ws-new'));

    // Workspace dir event and non-transcript file event must not trigger a full glob scan.
    writeFileSync(join(newDir, 'scratch.tmp'), 'ignore\n');
    internal.handleRootWatchEvent(sessionsDir, sessionsDir, watch, contextSchema, 'ws-a');
    internal.handleRootWatchEvent(sessionsDir, sessionsDir, watch, contextSchema, join('ws-a', 'session-2', 'scratch.tmp'));
    expect(scanSpy).not.toHaveBeenCalled();
    expect(internal.tailers.has(join(newDir, 'scratch.tmp'))).toBe(false);

    // Direct event on the new transcript file adds its tailer without calling resolveWatchFiles.
    internal.handleRootWatchEvent(sessionsDir, sessionsDir, watch, contextSchema, join('ws-a', 'session-2', 'session.jsonl'));
    expect(scanSpy).not.toHaveBeenCalled();
    await waitFor(() => loadWatchState(statePath).cwds?.[newFile] === '/ws-new');
    expect(internal.tailers.has(newFile)).toBe(true);
  });

  it('discovers a transcript inside a newly moved session directory without scanning the watch root', async () => {
    const sessionsDir = join(tmpRoot, 'sessions');
    mkdirSync(join(sessionsDir, 'ws-a'), { recursive: true });
    const statePath = join(tmpRoot, 'state.json');

    const watch: WatchTarget = { name: 'dsh', path: sessionsDir, schema: contextSchema };
    const watcher = new TranscriptWatcher({ version: 1, watches: [watch] }, statePath, 'in-process', 0);
    watchers.push(watcher);
    await watcher.start();

    const internal = watcher as any;
    for (const rw of internal.rootWatchers.splice(0)) rw.close();
    const scanSpy = spyOn(internal, 'resolveWatchFiles');

    const movedDir = join(sessionsDir, 'ws-a', 'session-moved');
    mkdirSync(movedDir, { recursive: true });
    const movedFile = join(movedDir, 'session.jsonl');
    writeFileSync(movedFile, contextLine('/ws-moved'));

    internal.handleRootWatchEvent(sessionsDir, sessionsDir, watch, contextSchema, join('ws-a', 'session-moved'));
    expect(scanSpy).not.toHaveBeenCalled();
    await waitFor(() => loadWatchState(statePath).cwds?.[movedFile] === '/ws-moved');
    expect(internal.tailers.has(movedFile)).toBe(true);
  });

  it('skips rescanning while a newly discovered file is still in startingTailers', () => {
    const sessionsDir = join(tmpRoot, 'sessions');
    mkdirSync(sessionsDir, { recursive: true });
    const pattern = join(sessionsDir, '**', '*.jsonl');
    const watch: WatchTarget = { name: 'codex', path: pattern, schema: contextSchema };
    const watcher = new TranscriptWatcher({ version: 1, watches: [watch] }, join(tmpRoot, 'state.json'), 'in-process', 0);
    watchers.push(watcher);

    const internal = watcher as any;
    const inFlightFile = join(sessionsDir, '2026', 'rollout-new.jsonl');
    internal.startingTailers.add(inFlightFile);
    const scanSpy = spyOn(internal, 'resolveWatchFiles');

    internal.handleRootWatchEvent(sessionsDir, pattern, watch, contextSchema, join('2026', 'rollout-new.jsonl'));
    expect(scanSpy).not.toHaveBeenCalled();
  });

  it('discovers a literal non-.jsonl file target without rescanning and ignores siblings', async () => {
    const target = join(tmpRoot, 'session.json');
    const sibling = join(tmpRoot, 'sibling.json');
    const statePath = join(tmpRoot, 'state.json');
    const watch: WatchTarget = { name: 'single', path: target, schema: contextSchema };
    const watcher = new TranscriptWatcher({ version: 1, watches: [watch] }, statePath, 'in-process', 0);
    watchers.push(watcher);
    await watcher.start();

    const internal = watcher as any;
    for (const rw of internal.rootWatchers.splice(0)) rw.close();
    const scanSpy = spyOn(internal, 'resolveWatchFiles');

    writeFileSync(sibling, contextLine('/sibling'));
    internal.handleRootWatchEvent(tmpRoot, target, watch, contextSchema, 'sibling.json');
    expect(scanSpy).not.toHaveBeenCalled();
    expect(internal.tailers.has(sibling)).toBe(false);

    writeFileSync(target, contextLine('/single'));
    internal.handleRootWatchEvent(tmpRoot, target, watch, contextSchema, 'session.json');
    expect(scanSpy).not.toHaveBeenCalled();
    await waitFor(() => loadWatchState(statePath).cwds?.[target] === '/single');
    expect(internal.tailers.has(target)).toBe(true);
  });
});