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

9.2 KB
Raw Blame

import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
import { readFileSync } from 'fs';
import { join } from 'path';
import { antigravityCliAdapter } from '../../../src/cli/adapters/antigravity-cli.js';
import { ingestObservation, setIngestContext } from '../../../src/services/worker/http/shared.js';
import { logger } from '../../../src/utils/logger.js';

// The Bash-pattern skip is a pure early return in ingestObservation, before any
// database access, so a stub context is enough. CLAUDE_MEM_SKIP_BASH_PATTERNS is
// applied through the env override in SettingsDefaultsManager.loadFromFile.
describe('ingestObservation — CLAUDE_MEM_SKIP_BASH_PATTERNS', () => {
  let prevPattern: string | undefined;
  let prevMatchEverySegment: string | undefined;

  beforeEach(() => {
    prevPattern = process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS;
    prevMatchEverySegment = process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT;
    delete process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT;
    setIngestContext({
      sessionManager: {} as any,
      dbManager: {} as any,
      eventBroadcaster: {} as any,
    });
  });

  afterEach(() => {
    if (prevPattern === undefined) delete process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS;
    else process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = prevPattern;
    if (prevMatchEverySegment === undefined) delete process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT;
    else process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT = prevMatchEverySegment;
  });

  const bash = (command: string) =>
    ingestObservation({
      contentSessionId: 'test-session',
      toolName: 'Bash',
      toolInput: { command },
      toolResponse: {},
    });

  it('skips a Bash command that matches the pattern', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat|pwd)\\b';
    const result = await bash('ls -la');
    expect(result).toEqual({ ok: true, status: 'skipped', reason: 'bash_pattern_excluded' });
  });

  it('keeps a compound command if any segment does not match in opt-in mode', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat|pwd)\\b';
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT = 'true';
    await expect(bash('cat a && rm -rf b')).rejects.toThrow();
  });

  it('skips only when every compound segment matches, respecting quoted separators', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat|pwd)\\b';
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT = 'true';
    expect(await bash('cat "a;b" && pwd; ls | cat')).toEqual({ ok: true, status: 'skipped', reason: 'bash_pattern_excluded' });
  });

  it('keeps ambiguous shell syntax in opt-in mode', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat|pwd)\\b';
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT = 'true';
    for (const command of ['ls $(touch x)', 'ls "$(touch x)"', 'ls > out', 'cat <(echo x)', 'ls `touch x`', 'ls "unterminated', 'ls \\', 'ls # comment', 'ls %VAR%', 'ls ^& rm', "ls '%VAR%'", "ls 'a & rm'", "ls ' >out'", "ls ' <in'", 'ls "a\nrm"']) {
      await expect(bash(command)).rejects.toThrow();
    }
  });

  it('applies the opt-in to PowerShell and Codex shell observations too', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat|pwd)\\b';
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT = 'true';
    for (const [toolName, toolInput] of [
      ['PowerShell', { command: 'ls; rm -r b' }],
      ['exec_command', { cmd: 'ls && rm -rf b' }],
    ] as const) {
      await expect(ingestObservation({ contentSessionId: 'test-session', toolName, toolInput, toolResponse: {} })).rejects.toThrow();
    }
  });

  it('retains whole-command matching when the opt-in is absent', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat|pwd)\\b';
    expect(await bash('cat a && rm -rf b')).toEqual({ ok: true, status: 'skipped', reason: 'bash_pattern_excluded' });
  });

  it('does not introduce skips for commands that failed whole-command matching', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|pwd)$';
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT = 'true';
    await expect(bash('ls && pwd')).rejects.toThrow();
  });

  // The trade-off the docs state: per-segment matching keeps any command with
  // a `$`, so a pattern used to keep secrets out of capture stops skipping it.
  it('captures a command with a variable that a secret pattern skips when the opt-in is off', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = 'password';
    expect(await bash('echo password=$SECRET')).toEqual({ ok: true, status: 'skipped', reason: 'bash_pattern_excluded' });

    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS_MATCH_EVERY_SEGMENT = 'true';
    await expect(bash('echo password=$SECRET')).rejects.toThrow();
    // Without a variable, backslash or other kept syntax the pattern still skips it.
    expect(await bash('echo password=Hunter22Example')).toEqual({ ok: true, status: 'skipped', reason: 'bash_pattern_excluded' });
  });

  // A command that is not skipped falls through to the database path, which the
  // stub context has no store for. The reject proves the Bash branch let it pass.
  it('does not skip a Bash command that fails to match', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat|pwd)\\b';
    await expect(bash('git commit -m "fix"')).rejects.toThrow();
  });

  it('skips a Codex exec_command whose cmd matches the pattern', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat|pwd)\\b';
    const result = await ingestObservation({
      contentSessionId: 'test-session',
      toolName: 'exec_command',
      toolInput: { cmd: 'pwd' },
      toolResponse: {},
    });
    expect(result).toEqual({ ok: true, status: 'skipped', reason: 'bash_pattern_excluded' });
  });

  // #4745: on Windows, Claude Code runs shell commands through the PowerShell tool.
  it('skips a PowerShell command that matches the pattern', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = 'password';
    const result = await ingestObservation({
      contentSessionId: 'test-session',
      toolName: 'PowerShell',
      toolInput: { command: 'echo password=Hunter22Example' },
      toolResponse: {},
    });
    expect(result).toEqual({ ok: true, status: 'skipped', reason: 'bash_pattern_excluded' });
  });

  it('does not skip a PowerShell command that fails to match', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat|pwd)\\b';
    await expect(ingestObservation({
      contentSessionId: 'test-session',
      toolName: 'PowerShell',
      toolInput: { command: 'Get-ChildItem -Force' },
      toolResponse: {},
    })).rejects.toThrow();
  });

  it('reads the PowerShell command from `command`, not other keys', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '.*';
    await expect(ingestObservation({
      contentSessionId: 'test-session',
      toolName: 'PowerShell',
      toolInput: { script: 'pwd' },
      toolResponse: {},
    })).rejects.toThrow();
  });

  // Antigravity's agy names its shell tool `run_command`. This is the
  // PostToolUse agy 1.4.9 sent for `ls -la`, through the agy adapter.
  const agyLsLa = () => {
    const fixture = JSON.parse(readFileSync(join(import.meta.dir, '../../fixtures/hosts/antigravity-cli-1.4.9-post-tool-use.json'), 'utf8'));
    const input = antigravityCliAdapter.normalizeInput(fixture.runCommand);
    return ingestObservation({
      contentSessionId: input.sessionId!,
      platformSource: 'antigravity-cli',
      toolName: input.toolName!,
      toolInput: input.toolInput,
      toolResponse: input.toolResponse,
    });
  };

  it('skips an Antigravity run_command that matches the pattern', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(ls|cat|pwd)\\b';
    expect(await agyLsLa()).toEqual({ ok: true, status: 'skipped', reason: 'bash_pattern_excluded' });
  });

  it('does not skip an Antigravity run_command that fails to match', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '^(cat|pwd)\\b';
    await expect(agyLsLa()).rejects.toThrow();
  });

  it('never applies the pattern to non-shell tools', async () => {
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '.*';
    await expect(ingestObservation({
      contentSessionId: 'test-session',
      toolName: 'Grep',
      toolInput: { command: 'ls', pattern: 'x' },
      toolResponse: {},
    })).rejects.toThrow();
  });

  it('warns once for a persistent invalid regex, not on every observation', async () => {
    // A unique value so the module-level compile cache has not seen it yet.
    process.env.CLAUDE_MEM_SKIP_BASH_PATTERNS = '(only-warn-once-' + process.pid;
    const warnings: string[] = [];
    const original = logger.warn;
    (logger as { warn: typeof logger.warn }).warn = ((_c: unknown, message: string) => {
      warnings.push(message);
    }) as typeof logger.warn;
    try {
      await expect(bash('ls -la')).rejects.toThrow();
      await expect(bash('ls -la')).rejects.toThrow();
    } finally {
      (logger as { warn: typeof logger.warn }).warn = original;
    }
    const invalidWarnings = warnings.filter(m => m.includes('CLAUDE_MEM_SKIP_BASH_PATTERNS'));
    expect(invalidWarnings.length).toBe(1);
  });
});