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

40.1 KB
Raw Blame
import { describe, it, expect } from 'bun:test';
import { readFileSync, existsSync, mkdtempSync, mkdirSync, writeFileSync, rmSync, utimesSync, chmodSync, realpathSync } from 'fs';
import { tmpdir } from 'os';
import { spawnSync } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';
import {
  buildCodexWindowsCommand,
  buildShellCommand,
} from '../../src/build/hook-shell-template.js';
import { HOOK_TIMEOUTS } from '../../src/shared/hook-constants.js';
import { FILE_CONTEXT_WORKER_BUDGET_MS } from '../../src/cli/handlers/file-context.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const projectRoot = path.resolve(__dirname, '../..');

function readJson(relativePath: string): any {
  return JSON.parse(readFileSync(path.join(projectRoot, relativePath), 'utf-8'));
}

function commandHookEntriesFrom(relativePath: string): any[] {
  const parsed = readJson(relativePath);
  return Object.values(parsed.hooks ?? {}).flatMap((matchers: any) =>
    matchers.flatMap((matcher: any) =>
      (matcher.hooks ?? []).filter((hook: any) => hook.type === 'command')
    )
  );
}

function mcpStartupCommandFrom(relativePath: string): string {
  const parsed = readJson(relativePath);
  return parsed.mcpServers['mcp-search'].args[1];
}

function posixPath(p: string): string {
  return p.replace(/\\/g, '/');
}

/** Map Windows %TEMP% paths to Git bash /tmp/... so shell-eval assertions match locally and on CI. */
function normalizeShellPath(p: string): string {
  const posix = posixPath(p).replace(/\/+$/, '');
  const tempMapped = posix.match(
    /^(?:[A-Za-z]:)?\/(?:Users\/[^/]+\/)?AppData\/Local\/Temp\/(.+)$/i,
  );
  if (tempMapped) {
    return `/tmp/${tempMapped[1]}`;
  }
  return posix;
}

function expectResolvedPath(stdout: string, expectedRoot: string): void {
  const match = stdout.match(/RESOLVED=(.+)/);
  expect(match).not.toBeNull();
  expect(realpathSync(match![1].trim())).toBe(realpathSync(expectedRoot));
}

function bashExecutable(): string {
  if (process.platform === 'win32') {
    const gitBash = 'C:/Program Files/Git/bin/bash.exe';
    if (existsSync(gitBash)) {
      return gitBash;
    }
  }
  return 'bash';
}

function installFakeNvmNode(home: string, version: string): string {
  const nodeBin = path.join(home, '.nvm', 'versions', 'node', `v${version}`, 'bin');
  mkdirSync(nodeBin, { recursive: true });
  const nodePath = path.join(nodeBin, 'node');
  writeFileSync(nodePath, '#!/bin/sh\nprintf "NODE=%s\\nPATH=%s\\n" "$0" "$PATH"\n');
  chmodSync(nodePath, 0o755);
  return nodeBin;
}

function shellEval(command: string, env: Record<string, string>): { status: number | null; stdout: string; stderr: string } {
  const result = spawnSync(bashExecutable(), ['-c', command], {
    env: { PATH: process.env.PATH ?? '', ...env },
    encoding: 'utf-8',
  });
  return { status: result.status, stdout: result.stdout ?? '', stderr: result.stderr ?? '' };
}

describe('Plugin Distribution - Skills', () => {
  const skillPath = path.join(projectRoot, 'plugin/skills/mem-search/SKILL.md');

  it('should have valid YAML frontmatter with name and description', () => {
    const content = readFileSync(skillPath, 'utf-8');

    expect(content.startsWith('---\n')).toBe(true);

    const frontmatterEnd = content.indexOf('\n---\n', 4);
    expect(frontmatterEnd).toBeGreaterThan(0);

    const frontmatter = content.slice(4, frontmatterEnd);
    expect(frontmatter).toContain('name:');
    expect(frontmatter).toContain('description:');
  });
});

describe('Plugin Distribution - Required Files', () => {
  it('should include claude-mem-grok-bot/skills/host-observer/SKILL.md', () => {
    expect(existsSync(path.join(projectRoot, 'claude-mem-grok-bot/skills/host-observer/SKILL.md'))).toBe(true);
  });
});

describe('Plugin Distribution - Devin', () => {
  it('ships a Devin manifest whose only MCP source is the Devin MCP file', () => {
    const manifest = readJson('plugin/.devin-plugin/plugin.json');
    expect(manifest.name).toBe('claude-mem');
    expect(manifest.mcpServers).toEqual({ paths: ['devin.mcp.json'], exclusive: true });
    const mcp = readJson('plugin/devin.mcp.json');
    expect(Object.keys(mcp.mcpServers)).toEqual(['claude-mem']);
    const launch = mcp.mcpServers['claude-mem'].args.join(' ');
    expect(launch).toContain('/mcp-server.cjs');
    expect(launch).toContain('command -v bun');
    expect(launch).toContain('${CLAUDE_CONFIG_DIR:-$HOME/.claude}');
  });

  it('routes every Devin lifecycle hook to the devin adapter of the installed worker', () => {
    const hooks = readJson('plugin/hooks.json');
    const commands: Record<string, string[]> = {};
    for (const [event, rules] of Object.entries(hooks) as [string, any[]][]) {
      commands[event] = rules.flatMap((rule) => rule.hooks.map((hook: any) => hook.command));
    }
    const suffix = (command: string) => command.match(/worker-service\.cjs" (.+)'$/)?.[1];
    expect(Object.fromEntries(Object.entries(commands).map(([event, list]) => [event, list.map(suffix)]))).toEqual({
      SessionStart: ['start', 'hook devin context'],
      PostCompaction: ['hook devin context'],
      UserPromptSubmit: ['hook devin session-init'],
      PostToolUse: ['hook devin observation'],
      Stop: ['hook devin summarize'],
      SessionEnd: ['hook devin session-end'],
    });
    expect(Object.keys(hooks)).not.toContain('PreToolUse');
  });
});

describe('Plugin Distribution - Qoder', () => {
  it('ships root and bundled manifests with the correct relative paths', () => {
    const root = readJson('.qoder-plugin/plugin.json');
    const bundled = readJson('plugin/.qoder-plugin/plugin.json');
    expect(root.hooks).toBe('./plugin/hooks/qoder-repo-hooks.json');
    expect(root.mcpServers).toBe('./plugin/qoder.mcp.json');
    expect(bundled.hooks).toBe('./hooks/qoder-hooks.json');
    expect(bundled.mcpServers).toBe('./qoder.mcp.json');
  });

  it('runs every Qoder hook through the structured hook launcher', () => {
    for (const file of ['plugin/hooks/qoder-hooks.json', 'plugin/hooks/qoder-repo-hooks.json']) {
      const entries = commandHookEntriesFrom(file);
      expect(entries.length).toBeGreaterThan(0);
      for (const entry of entries) {
        expect(entry.command).toBe('node');
        expect(entry.args.join(' ')).toContain('qoder-hook-launcher.cjs');
        expect(entry.env.CLAUDE_MEM_CODEX_HOOK).toBe('1');
      }
    }
  });

  it('gives first-session dependency setup enough time to complete', () => {
    for (const file of ['plugin/hooks/qoder-hooks.json', 'plugin/hooks/qoder-repo-hooks.json']) {
      const hooks = readJson(file);
      expect(hooks.hooks.SessionStart[0].hooks[0].timeout).toBe(180);
    }
  });
});

describe('Plugin Distribution - Codex Marketplace', () => {
  it('re-injects Codex memory on every SessionStart source that starts a fresh context', () => {
    // Codex emits startup, resume, clear and compact, and since 0.165 fork for
    // its attached thread forks (SessionStartSource in
    // codex-rs/hooks/src/events/session_start.rs). clear and compact both hand
    // the model an empty context, so the injection hook has to run for them or
    // the session continues with no memory; a fork starts a new thread that
    // needs memory too.
    const codexHooks = readJson('plugin/hooks/codex-hooks.json');
    const matchers = codexHooks.hooks.SessionStart.map((entry: any) => entry.matcher);

    expect(matchers).toHaveLength(1);
    for (const source of ['startup', 'resume', 'clear', 'compact', 'fork']) {
      expect(matchers[0].split('|')).toContain(source);
    }
  });

  it('marks every Codex compaction so the next PostToolUse can re-inject memory', () => {
    // PostCompact cannot emit additionalContext, and Codex never sends
    // SessionStart to a subagent thread, so PostCompact marks the thread and its
    // next PostToolUse (registered for every tool) carries the timeline back.
    const codexHooks = readJson('plugin/hooks/codex-hooks.json');
    const postCompact = codexHooks.hooks.PostCompact;

    expect(postCompact).toHaveLength(1);
    // No matcher: Codex then matches every compaction trigger (manual and auto).
    expect(postCompact[0].matcher).toBeUndefined();
    expect(postCompact[0].hooks).toHaveLength(1);
    expect(postCompact[0].hooks[0].command).toContain('hook codex post-compact');
    expect(codexHooks.hooks.PostToolUse[0].matcher).toBe('.*');
  });

  it('gives a subagent Codex starts its memory timeline', () => {
    // Codex starts a spawned subagent with SubagentStart instead of SessionStart
    // (run_pending_session_start_hooks in codex-rs/core/src/hook_runtime.rs).
    const codexHooks = readJson('plugin/hooks/codex-hooks.json');
    const subagentStart = codexHooks.hooks.SubagentStart;

    expect(subagentStart).toHaveLength(1);
    // No matcher: Codex matches it against the agent type, and every type gets memory.
    expect(subagentStart[0].matcher).toBeUndefined();
    expect(subagentStart[0].hooks).toHaveLength(1);
    expect(subagentStart[0].hooks[0].command).toContain('hook codex subagent-context');
  });

  it('bounds the synchronous Codex observation hook to a short fail-open wait', () => {
    const codexHooks = readJson('plugin/hooks/codex-hooks.json');
    const observation = codexHooks.hooks.PostToolUse[0].hooks[0];

    expect(observation.command).toContain('hook codex observation');
    expect(observation.timeout).toBe(5);
    expect(observation).not.toHaveProperty('async');

    for (const event of ['SessionStart', 'UserPromptSubmit', 'PreToolUse', 'Stop', 'PostCompact', 'SubagentStart']) {
      expect(codexHooks.hooks[event][0].hooks[0]).not.toHaveProperty('async');
    }
  });

  it('sets Windows Codex hook overrides without POSIX-only shell syntax', () => {
    const entries = commandHookEntriesFrom('plugin/hooks/codex-hooks.json');
    const posixOnlyTokens = ['$(', '${', '[ -', 'printenv', 'export PATH', 'command -v', '2>/dev/null', 'while IFS'];

    expect(entries.length).toBeGreaterThan(0);
    for (const entry of entries) {
      expect(typeof entry.commandWindows).toBe('string');
      expect(entry.commandWindows).toContain('node -e');
      expect(entry.commandWindows).toContain('CLAUDE_MEM_CODEX_HOOK');
      expect(entry.commandWindows).toContain('bun-runner.js');
      expect(entry.commandWindows).toContain('worker-service.cjs');
      expect(entry.commandWindows).toContain('plugins');
      expect(entry.commandWindows).toContain('cache');
      expect(entry.commandWindows).toContain('marketplaces');
      for (const token of posixOnlyTokens) {
        expect(entry.commandWindows).not.toContain(token);
      }
    }
  });

  it('ships a single Codex SessionStart command', () => {
    const codexHooks = readJson('plugin/hooks/codex-hooks.json');
    expect(codexHooks.hooks.SessionStart[0].hooks).toHaveLength(1);
    expect(codexHooks.hooks.SessionStart[0].hooks[0].command).not.toContain('version-check.js');
    expect(codexHooks.hooks.SessionStart[0].hooks[0].commandWindows).not.toContain('version-check.js');
  });
});

describe('Plugin Distribution - Cursor Marketplace', () => {
  it('ships independent Cursor and Grok Bot marketplace entries', () => {
    const marketplace = readJson('.cursor-plugin/marketplace.json');
    expect(marketplace.owner.name).toBe('Alex Newman');
    expect(marketplace.plugins.map((plugin: any) => plugin.name)).toEqual([
      'claude-mem-cursor',
      'claude-mem-grok-bot',
    ]);
  });

  it('wires Cursor hooks through the npx hook entrypoint', () => {
    const hooks = readJson('claude-mem-cursor/hooks/hooks.json');
    expect(hooks.hooks.beforeSubmitPrompt[0].command).toContain('npx -y claude-mem hook cursor session-init');
    expect(hooks.hooks.stop[0].command).toContain('npx -y claude-mem hook cursor summarize');
  });

  it('ships the shared local and remote MCP definitions for both plugins', () => {
    for (const relativePath of ['claude-mem-cursor/mcp.json', 'claude-mem-grok-bot/mcp.json']) {
      const mcp = readJson(relativePath);
      expect(mcp.mcpServers['claude-mem-local'].args).toEqual(['-y', 'claude-mem', 'mcp']);
      const expected = 'Bearer ' + '${' + 'CLAUDE_MEM_MCP_TOKEN' + '}';
      expect(mcp.mcpServers['claude-mem-remote'].headers.Authorization).toBe(expected);
    }
  });
});

describe('Plugin Distribution - hooks.json Integrity', () => {
  it('includes the launcher self-heal script', () => {
    expect(existsSync(path.join(projectRoot, 'plugin/scripts/ensure-launcher.cjs'))).toBe(true);
  });

  // The Setup entry is the only shell-form hook left (it fires only on
  // `claude --init` / `--maintenance`, SPIKE item 8), so the defensive bash
  // root-resolution contract is pinned on it alone.
  const setupCommand = () => String(readJson('plugin/hooks/hooks.json').hooks.Setup[0].hooks[0].command);

  it('should include CLAUDE_PLUGIN_ROOT fallback in the Setup hook command (#1215)', () => {
    expect(setupCommand()).toContain('$_C/plugins/marketplaces/thedotmack/plugin');
  });

  it('should try cache path before marketplaces fallback in the Setup hook command (#1533)', () => {
    const cachePath = '$_C/plugins/cache/thedotmack/claude-mem';
    const marketplacesPath = '$_C/plugins/marketplaces/thedotmack/plugin';
    const command = setupCommand();
    expect(command).toContain(cachePath);
    expect(command.indexOf(cachePath)).toBeLessThan(command.indexOf(marketplacesPath));
  });

  it('should quote NVM ls path inside export PATH in the Setup hook (#3190)', () => {
    const command = setupCommand();
    expect(command).toMatch(/ls "\$HOME\/\.nvm\/versions\/node"/);
    expect(command).not.toMatch(/ls \\"\$HOME\/\.nvm\/versions\/node\\"/);
  });
});

describe('Plugin Distribution - Startup Root Resolution', () => {
  it('MCP startup command resolves the plugin root cross-platform (#2792)', () => {
    // The launcher is now a cross-platform `node -e` payload (no `sh`), so it
    // runs on Windows without Git Bash. It must still resolve the plugin root
    // with config-dir + env fallbacks and try cache roots before marketplaces.
    const command = mcpStartupCommandFrom('plugin/.mcp.json');

    expect(command).toContain('CLAUDE_CONFIG_DIR');
    expect(command).toContain('.claude');
    expect(command).toContain('CLAUDE_PLUGIN_ROOT');
    expect(command).toContain('PLUGIN_ROOT');
    expect(command).toContain('plugins/marketplaces/thedotmack/plugin');
    expect(command).toContain('plugins/cache/thedotmack/claude-mem');
    expect(command).toContain('mcp-server.cjs');
    expect(command).toMatch(/require\(p\.resolve\(R,'scripts',["']mcp-server\.cjs["']\)\)/);
    expect(command).not.toContain('child_process');
    expect(command).not.toContain('.spawn(');
    // No bare absolute "/scripts/..." path leaks through.
    expect(command).not.toContain('"/scripts/mcp-server.cjs"');
    expect(command.indexOf('plugins/cache/thedotmack/claude-mem')).toBeLessThan(
      command.indexOf('plugins/marketplaces/thedotmack/plugin')
    );
  });
});

describe('Plugin Distribution - MCP launcher process (#4269)', () => {
  // Runs the shipped plugin/.mcp.json entry against a fixture server that
  // prints its own pid. Loaded in-process, the server's pid is the launcher's,
  // so each MCP session costs one Node process rather than an idle launcher
  // plus a child.
  const { command, args } = readJson('plugin/.mcp.json').mcpServers['mcp-search'];

  function launchMcpServer(pluginRootFor: ((sandbox: string) => string) | null) {
    const sandbox = mkdtempSync(path.join(tmpdir(), 'claude-mem-mcp-launch-'));
    try {
      mkdirSync(path.join(sandbox, 'fixture', 'scripts'), { recursive: true });
      writeFileSync(path.join(sandbox, 'fixture', 'scripts', 'mcp-server.cjs'), 'process.stdout.write(String(process.pid));\n');
      // An empty HOME and config dir, so no real install can satisfy a candidate.
      const home = path.join(sandbox, 'home');
      const configDir = path.join(sandbox, 'claude-config');
      mkdirSync(home);
      mkdirSync(configDir);
      const env: Record<string, string | undefined> = { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: configDir };
      delete env.CLAUDE_PLUGIN_ROOT;
      delete env.PLUGIN_ROOT;
      if (pluginRootFor) env.CLAUDE_PLUGIN_ROOT = pluginRootFor(sandbox);
      return spawnSync(command, args, { cwd: sandbox, env, encoding: 'utf-8', timeout: 20000 });
    } finally {
      rmSync(sandbox, { recursive: true, force: true });
    }
  }

  it('runs the server inside the launcher process for an absolute plugin root', () => {
    const result = launchMcpServer(sandbox => path.join(sandbox, 'fixture'));
    expect(result.status, result.stderr).toBe(0);
    expect(result.stdout).toBe(String(result.pid));
  });

  it('resolves a relative plugin root against the working directory', () => {
    const result = launchMcpServer(() => './fixture');
    expect(result.status, result.stderr).toBe(0);
    expect(result.stdout).toBe(String(result.pid));
  });

  it('exits 1 with the not-found message when no candidate has the server', () => {
    const result = launchMcpServer(null);
    expect(result.status).toBe(1);
    expect(result.stderr).toContain('claude-mem: mcp server not found');
  });
});

describe('Plugin Distribution - package.json Files Field', () => {
  it('runs bug-report from the bundled distribution entry', () => {
    const packageJson = readJson('package.json');

    expect(packageJson.scripts['bug-report']).toBe('node dist/bug-report/index.js');
    expect(packageJson.files).toContain('dist');
  });

  it('should include bundled plugin entries in root package.json files field', () => {
    const packageJsonPath = path.join(projectRoot, 'package.json');
    const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
    expect(packageJson.files).toBeDefined();
    expect(packageJson.files).toContain('plugin/.codex-plugin');
    expect(packageJson.files).toContain('plugin/.mcp.json');
    expect(packageJson.files).toContain('plugin/hooks');
    expect(packageJson.files).toContain('plugin/skills');
    expect(packageJson.files).toContain('plugin/scripts/*.cjs');
    expect(packageJson.files).toContain('plugin/sqlite');
  });

  it('npm tarball includes generated runtime entries and the Claude marketplace root manifests (#3424)', () => {
    const result = spawnSync('npm', ['pack', '--dry-run', '--json'], {
      cwd: projectRoot,
      encoding: 'utf-8',
    });

    expect(result.status).toBe(0);
    const packed = JSON.parse(result.stdout);
    // npm 12 keys pack results by package name; older npm returns an array.
    const artifact = Array.isArray(packed) ? packed[0] : packed[readJson('package.json').name];
    const filePaths = new Set(artifact.files.map((file: { path: string }) => file.path));

    expect(filePaths.has('dist/bug-report/index.js')).toBe(true);
    expect(filePaths.has('plugin/sqlite/SessionStore.js')).toBe(true);
    expect(filePaths.has('plugin/sqlite/observations/files.js')).toBe(true);
    expect(filePaths.has('.claude-plugin/marketplace.json')).toBe(true);
    expect(filePaths.has('.claude-plugin/plugin.json')).toBe(true);
  }, 30_000);
});

describe('Plugin Distribution - Setup Hook (#1547)', () => {
  it('should not reference removed setup.sh in Setup hook', () => {
    const hooksPath = path.join(projectRoot, 'plugin/hooks/hooks.json');
    const content = readFileSync(hooksPath, 'utf-8');
    expect(content).not.toContain('setup.sh');
  });

  it('version-check.js referenced by Setup hook should exist on disk', () => {
    const versionCheckPath = path.join(projectRoot, 'plugin/scripts/version-check.js');
    expect(existsSync(versionCheckPath)).toBe(true);
  });
});

describe('Plugin Distribution - Non-blocking bookkeeping hooks (#3206)', () => {
  it('runs observation, summarization, and SessionEnd asynchronously', () => {
    const hooksPath = path.join(projectRoot, 'plugin/hooks/hooks.json');
    const parsed = JSON.parse(readFileSync(hooksPath, 'utf-8'));

    const postToolUse = parsed.hooks.PostToolUse[0].hooks[0];
    const postToolUseFailure = parsed.hooks.PostToolUseFailure[0].hooks[0];
    const stop = parsed.hooks.Stop[0].hooks[0];
    const sessionEnd = parsed.hooks.SessionEnd[0].hooks[0];
    const subagentStop = parsed.hooks.SubagentStop[0].hooks[0];

    expect(postToolUse.args).toEqual(['hook', 'claude-code', 'observation']);
    expect(postToolUse.async).toBe(true);
    expect(parsed.hooks.PostToolUseFailure[0].matcher).toBe('*');
    expect(postToolUseFailure.args).toEqual(['hook', 'claude-code', 'observation']);
    expect(postToolUseFailure.async).toBe(true);
    expect(stop.args).toEqual(['hook', 'claude-code', 'summarize']);
    expect(stop.async).toBe(true);
    expect(sessionEnd.args).toEqual(['hook', 'claude-code', 'session-end']);
    expect(sessionEnd.async).toBe(true);
    expect(subagentStop.args).toEqual(['hook', 'claude-code', 'subagent-stop']);
    expect(subagentStop.async).toBe(true);
  });

  it('runs the SessionStart worker start asynchronously and keeps context and UserPromptSubmit synchronous (#3303)', () => {
    const hooksPath = path.join(projectRoot, 'plugin/hooks/hooks.json');
    const parsed = JSON.parse(readFileSync(hooksPath, 'utf-8'));

    const sessionStart = parsed.hooks.SessionStart.flatMap((group: any) => group.hooks);
    const workerStart = sessionStart.find((hook: any) => hook.command === 'claude-mem' && hook.args?.[0] === 'start');
    const context = sessionStart.find((hook: any) => hook.command === 'claude-mem' && hook.args?.join(' ') === 'hook claude-code context');
    const userPromptSubmit = parsed.hooks.UserPromptSubmit[0].hooks[0];

    // start, context, and the ensure-launcher self-heal.
    expect(sessionStart).toHaveLength(3);
    expect(parsed.hooks.SessionStart[1].matcher).toBe('startup|clear|compact');
    // #4969: /plugin update + /reload-plugins does not fire startup, so the
    // self-heal must also run on resume/clear/compact to place a missing launcher.
    const ensureEntry = parsed.hooks.SessionStart.find((entry: any) =>
      entry.hooks.some((hook: any) => hook.command === 'node' && String(hook.args?.[0]).endsWith('ensure-launcher.cjs')));
    expect(ensureEntry.matcher.split('|').sort()).toEqual(['clear', 'compact', 'resume', 'startup']);
    // `start` only prints a status envelope, and the context hook lazily
    // spawns the worker itself, so session start need not wait for it.
    expect(workerStart.async).toBe(true);
    // `context` must stay synchronous: Claude Code hands an async hook's
    // additionalContext / systemMessage to the model on the next turn and never
    // shows the systemMessage to the user, which would hide the startup
    // timeline, the viewer link and the trial notice.
    expect(context).not.toHaveProperty('async');
    expect(userPromptSubmit.args).toEqual(['hook', 'claude-code', 'session-init']);
    // Keep prompt-row persistence ordered before downstream hooks consume it.
    expect(userPromptSubmit).not.toHaveProperty('async');
  });

  it('keeps the PreToolUse Read file-context hook synchronous so the File Read Gate can deny', () => {
    const hooksPath = path.join(projectRoot, 'plugin/hooks/hooks.json');
    const parsed = JSON.parse(readFileSync(hooksPath, 'utf-8'));

    const preToolUseGroup = parsed.hooks.PreToolUse[0];
    const fileContext = preToolUseGroup.hooks[0];

    const matcher = new RegExp(preToolUseGroup.matcher);
    for (const tool of ['Read', 'Grep', 'Glob', 'memory_search', 'memory', 'mcp__native__memory_search']) {
      expect(matcher.test(tool)).toBe(true);
    }
    expect(matcher.test('save_memory')).toBe(false);
    expect(fileContext.args).toEqual(['hook', 'claude-code', 'file-context']);
    // Claude Code ignores permissionDecision from an async hook, so an async
    // file-context hook could never block a whole-file Read.
    expect(fileContext).not.toHaveProperty('async');
  });
});

// ---------------------------------------------------------------------------
// Spawn-contract templating
// ---------------------------------------------------------------------------

const ccTrailing = (...tail: string[]) => [
  'node', '"$_P/scripts/bun-runner.js"', '"$_P/scripts/worker-service.cjs"', ...tail,
];
const codexHook = (tail: string[]) => buildShellCommand({
  host: 'codex-cli', requireFile: 'bun-runner.js', requireFileSecondary: 'worker-service.cjs',
  trailingCommand: ccTrailing(...tail), notFoundMessage: 'claude-mem: plugin scripts not found',
  extraEnv: { CLAUDE_MEM_CODEX_HOOK: '1' },
  requireDependencies: true,
});
const codexHookPair = (tail: string[], entryOptions: Record<string, unknown> = {}) => ({
  command: codexHook(tail),
  commandWindows: buildCodexWindowsCommand(tail, { requireDependencies: true }),
  ...entryOptions,
});

const SESSION_INIT_HOOK_TIMEOUT_SECONDS = 15;
const SESSION_INIT_HOOK_PATH = 'UserPromptSubmit.0.0';
const FILE_CONTEXT_HOOK_TIMEOUT_SECONDS = 15;
const FILE_CONTEXT_HOOK_PATH = 'PreToolUse.0.0';

type RuleAExpectation = string | { command: string; commandWindows?: string; timeout?: number };

const SETUP_SHELL_COMMAND = buildShellCommand({
  host: 'claude-code-setup', requireFile: 'version-check.js',
  trailingCommand: ['node', '"$_P/scripts/version-check.js"'],
  notFoundMessage: 'claude-mem: version-check.js not found',
});

const RULE_A_EXPECTATIONS: Record<string, Record<string, RuleAExpectation>> = {
  'plugin/hooks/hooks.json': {
    'Setup.0.0': SETUP_SHELL_COMMAND,
  },
  'plugin/hooks/codex-hooks.json': {
    'SessionStart.0.0': codexHookPair(['hook', 'codex', 'context']),
    'UserPromptSubmit.0.0': codexHookPair(['hook', 'codex', 'session-init']),
    'PreToolUse.0.0': codexHookPair(['hook', 'codex', 'file-context']),
    'PostToolUse.0.0': codexHookPair(
      ['hook', 'codex', 'observation'],
      { timeout: 5 },
    ),
    'Stop.0.0': codexHookPair(['hook', 'codex', 'summarize']),
    'PostCompact.0.0': codexHookPair(['hook', 'codex', 'post-compact']),
    'SubagentStart.0.0': codexHookPair(['hook', 'codex', 'subagent-context']),
  },
};

const MCP_EXPECTED = buildShellCommand({
  // The mcp Node launcher derives its module target from requireFile; it ignores
  // trailingCommand, so none is passed (see buildMcpNodeLauncher).
  host: 'mcp', requireFile: 'mcp-server.cjs',
  notFoundMessage: 'claude-mem: mcp server not found',
  mcpExtraCandidates: ['$PWD/plugin', '$PWD'],
  mcpExtraCacheRoots: [
    '$HOME/.codex/plugins/cache/claude-mem-local/claude-mem',
    '$HOME/.codex/plugins/cache/thedotmack/claude-mem',
  ],
});

function hookEntryByPath(parsed: any, dottedPath: string): any | null {
  const [event, groupIdx, hookIdx] = dottedPath.split('.');
  return parsed.hooks?.[event]?.[Number(groupIdx)]?.hooks?.[Number(hookIdx)] ?? null;
}

function hookCommandByPath(parsed: any, dottedPath: string): string | null {
  return hookEntryByPath(parsed, dottedPath)?.command ?? null;
}

describe('Spawn-Contract Templating - hook budgets and placeholders', () => {
  it('bounds the Claude Code UserPromptSubmit hook below the legacy 60 second stall (#3434)', () => {
    const parsed = readJson('plugin/hooks/hooks.json');
    expect(hookEntryByPath(parsed, SESSION_INIT_HOOK_PATH)?.timeout).toBe(SESSION_INIT_HOOK_TIMEOUT_SECONDS);
    // The session-init budget must fit inside the host timeout with room for
    // launcher and bun startup.
    expect(HOOK_TIMEOUTS.SESSION_INIT_REQUEST_MAX).toBeLessThan(SESSION_INIT_HOOK_TIMEOUT_SECONDS * 1000);
    // Codex keeps its bounded startup (15 s wait + 2 s request) under 20 s.
    const codex = readJson('plugin/hooks/codex-hooks.json');
    expect(hookEntryByPath(codex, SESSION_INIT_HOOK_PATH)?.timeout).toBeGreaterThan(
      (HOOK_TIMEOUTS.POST_SPAWN_WAIT + 2_000) / 1000,
    );
  });

  it('bounds the synchronous Claude Code PreToolUse Read hook below the legacy 60 second stall', () => {
    const parsed = readJson('plugin/hooks/hooks.json');
    const timeoutSeconds = hookEntryByPath(parsed, FILE_CONTEXT_HOOK_PATH)?.timeout;
    expect(timeoutSeconds).toBe(FILE_CONTEXT_HOOK_TIMEOUT_SECONDS);
    // The handler's worker budget must fit inside the host timeout with room
    // for shell, node and bun startup.
    expect(timeoutSeconds).toBeGreaterThan(FILE_CONTEXT_WORKER_BUDGET_MS / 1000 + 5);
  });

  it('never leaks a raw ${CLAUDE_PLUGIN_ROOT} into the resolved trailing command', () => {
    // The placeholder may appear only inside the _E="${CLAUDE_PLUGIN_ROOT:-...}"
    // expansion, never as a bare `${CLAUDE_PLUGIN_ROOT}` token that would reach
    // the binary unsubstituted.
    const shCommands = Object.values(RULE_A_EXPECTATIONS).flatMap((c) =>
      Object.values(c).map((expectation) =>
        typeof expectation === 'string' ? expectation : expectation.command
      )
    );
    for (const command of shCommands) {
      expect(command).not.toMatch(/\$\{CLAUDE_PLUGIN_ROOT\}(?!:-)/);
      expect(command).toContain('_E="${CLAUDE_PLUGIN_ROOT:-${PLUGIN_ROOT:-}}"');
    }
    // The MCP node launcher reads env vars directly — it has no `${...}` shell
    // tokens at all, so a raw placeholder can never reach the binary.
    expect(MCP_EXPECTED).not.toContain('${CLAUDE_PLUGIN_ROOT}');
    expect(MCP_EXPECTED).toContain('process.env.CLAUDE_PLUGIN_ROOT');
    expect(MCP_EXPECTED).toContain('process.env.PLUGIN_ROOT');
  });
});

describe('Spawn-Contract Templating - Rule A shell resolution matrix', () => {
  // Claude Code runtime hooks are exec form now; their root-resolution cases
  // live in tests/launcher/claude-mem-launcher.test.ts. This matrix covers the
  // remaining shell-form sites: the Claude Setup hook and the Codex hooks.
  // Actually shell-evaluate the generated commands across resolution sources:
  // (a) CLAUDE_PLUGIN_ROOT injected, (b) cache fallback hit, (c) all miss.
  // Fixture scripts report their location after the complete hook resolves and runs them.
  function writeProbeScripts(root: string): void {
    mkdirSync(path.join(root, 'scripts'), { recursive: true });
    for (const file of ['version-check.js', 'bun-runner.js', 'worker-service.cjs']) {
      writeFileSync(path.join(root, 'scripts', file),
        "console.log('RESOLVED=' + require('path').dirname(__dirname));\n");
    }
  }

  const claudeCommands = () => {
    const parsed = readJson('plugin/hooks/hooks.json');
    return Object.entries(RULE_A_EXPECTATIONS['plugin/hooks/hooks.json']).map(
      ([dottedPath]) => ({ dottedPath, command: hookCommandByPath(parsed, dottedPath)! })
    );
  };

  it('resolves a valid CLAUDE_PLUGIN_ROOT without scanning the plugin cache (#3449, #4121)', () => {
    const root = mkdtempSync(path.join(tmpdir(), 'cm-root-'));
    const home = mkdtempSync(path.join(tmpdir(), 'cm-home-'));
    const shimBin = mkdtempSync(path.join(tmpdir(), 'cm-bin-'));
    const cacheScanMarker = path.join(home, 'cache-scan-ran');
    writeProbeScripts(root);
    // The Codex hooks require the host root's dependencies (#4763), so this
    // "valid root" carries node_modules like an installer-prepared copy.
    mkdirSync(path.join(root, 'node_modules'), { recursive: true });
    // Only the cache scan sorts with `sort -r`; the NVM PATH prelude sorts by
    // -t. keys. This shim records `-r` calls and passes input through.
    writeFileSync(
      path.join(shimBin, 'sort'),
      '#!/bin/sh\n[ "$1" = "-r" ] && printf touched > "$CACHE_SCAN_MARKER"\ncat\n',
    );
    chmodSync(path.join(shimBin, 'sort'), 0o755);

    const codexHooks = readJson('plugin/hooks/codex-hooks.json');
    const codexCommands = Object.keys(RULE_A_EXPECTATIONS['plugin/hooks/codex-hooks.json']).map(
      (dottedPath) => ({ dottedPath, command: hookCommandByPath(codexHooks, dottedPath)! }),
    );

    try {
      for (const { dottedPath, command } of [...claudeCommands(), ...codexCommands]) {
        rmSync(cacheScanMarker, { force: true });
        const { status, stdout } = shellEval(command, {
          CLAUDE_PLUGIN_ROOT: root,
          HOME: home,
          CACHE_SCAN_MARKER: posixPath(cacheScanMarker),
          PATH: `${shimBin}${path.delimiter}${process.env.PATH ?? ''}`,
        });
        expect({ dottedPath, status }).toEqual({ dottedPath, status: 0 });
        expectResolvedPath(stdout, root);
        expect({ dottedPath, cacheScanned: existsSync(cacheScanMarker) }).toEqual({ dottedPath, cacheScanned: false });
      }

      // Control: with an invalid CLAUDE_PLUGIN_ROOT the cache scan still runs,
      // so the shim above would have caught a fast path that never engaged.
      rmSync(cacheScanMarker, { force: true });
      const [{ command: setupCommand }] = claudeCommands().filter(
        ({ dottedPath }) => dottedPath === 'Setup.0.0',
      );
      shellEval(setupCommand, {
        CLAUDE_PLUGIN_ROOT: path.join(home, 'not-a-plugin-root'),
        HOME: home,
        CACHE_SCAN_MARKER: posixPath(cacheScanMarker),
        PATH: `${shimBin}${path.delimiter}${process.env.PATH ?? ''}`,
      });
      expect(existsSync(cacheScanMarker)).toBe(true);
    } finally {
      rmSync(root, { recursive: true, force: true });
      rmSync(home, { recursive: true, force: true });
      rmSync(shimBin, { recursive: true, force: true });
    }
  });

  it('skips a Codex host root whose dependencies are missing and falls back to the cache (#4763)', () => {
    // Codex's own plugin copy carries the scripts but never its dependencies:
    // the CLI rebuilds that folder on every `codex plugin add`, so a hook that
    // resolves to it dies with `Cannot find module 'zod/v3'` and the session
    // records nothing. The resolver must reject that root and fall back to the
    // installer-prepared cache copy instead. One hook proves the resolver
    // behavior; running all six only multiplies shell spawns.
    const codexRoot = mkdtempSync(path.join(tmpdir(), 'cm-codex-root-'));
    const home = mkdtempSync(path.join(tmpdir(), 'cm-home-'));
    const cacheRoot = path.join(home, '.claude', 'plugins', 'cache', 'thedotmack', 'claude-mem', '99.0.0');
    writeProbeScripts(codexRoot);
    // The Codex copy deliberately has no node_modules — that is the bug shape.
    writeProbeScripts(cacheRoot);
    // The prepared cache copy has the dependencies (the installer ran bun
    // install there); only the host root is dependency-checked, so it still
    // resolves.
    mkdirSync(path.join(cacheRoot, 'node_modules'), { recursive: true });

    const codexHooks = readJson('plugin/hooks/codex-hooks.json');
    const command = hookCommandByPath(codexHooks, 'SessionStart.0.0')!;

    try {
      const { status, stdout } = shellEval(command, {
        CLAUDE_PLUGIN_ROOT: codexRoot,
        HOME: home,
      });
      expect(status).toBe(0);
      expectResolvedPath(stdout, cacheRoot);
    } finally {
      rmSync(codexRoot, { recursive: true, force: true });
      rmSync(home, { recursive: true, force: true });
    }
  }, 30_000);

  describe('Codex Windows payload dependency check (#4763)', () => {
    // Runs the generated `node -e` payload for real. Each candidate root's
    // bun-runner.js is a stub that prints its own plugin root, so stdout names
    // the root the payload resolved and spawned.
    function runCodexWindowsPayload(hostRootHasDependencies: boolean) {
      const sandbox = mkdtempSync(path.join(tmpdir(), 'cm-codex-win-'));
      const makeRoot = (root: string, withDependencies: boolean) => {
        mkdirSync(path.join(root, 'scripts'), { recursive: true });
        writeFileSync(
          path.join(root, 'scripts', 'bun-runner.js'),
          "process.stdout.write(require('path').dirname(require('path').dirname(process.argv[1])));\n",
        );
        writeFileSync(path.join(root, 'scripts', 'worker-service.cjs'), '');
        if (withDependencies) mkdirSync(path.join(root, 'node_modules'));
        return root;
      };
      try {
        const home = path.join(sandbox, 'home');
        const configDir = path.join(home, '.claude');
        const hostRoot = makeRoot(path.join(sandbox, 'codex-plugin'), hostRootHasDependencies);
        const cacheRoot = makeRoot(path.join(configDir, 'plugins', 'cache', 'thedotmack', 'claude-mem', '99.0.0'), true);
        const command = buildCodexWindowsCommand(['hook', 'codex', 'session-init'], { requireDependencies: true });
        const env: Record<string, string | undefined> = {
          ...process.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: configDir, CLAUDE_PLUGIN_ROOT: hostRoot,
        };
        delete env.PLUGIN_ROOT;
        delete env.CLAUDE_MEM_DISABLE_TOOL_HOOKS;
        const result = spawnSync(command, { shell: true, cwd: sandbox, env, encoding: 'utf-8', timeout: 20000 });
        return {
          status: result.status,
          stderr: result.stderr,
          resolvedRoot: result.stdout ? realpathSync(result.stdout) : '',
          hostRoot: realpathSync(hostRoot),
          cacheRoot: realpathSync(cacheRoot),
        };
      } finally {
        rmSync(sandbox, { recursive: true, force: true });
      }
    }

    it('falls back to the cache when the host root has no node_modules', () => {
      const run = runCodexWindowsPayload(false);
      expect(run.status, run.stderr).toBe(0);
      expect(run.resolvedRoot).toBe(run.cacheRoot);
    });

    it('still prefers a host root that has its dependencies', () => {
      const run = runCodexWindowsPayload(true);
      expect(run.status, run.stderr).toBe(0);
      expect(run.resolvedRoot).toBe(run.hostRoot);
    });
  });

  it('prefers the highest cache version over the newest mtime and skips .orphaned_at dirs (2026-07-22 restart storm)', () => {
    const home = mkdtempSync(path.join(tmpdir(), 'cm-home-'));
    const cacheBase = path.join(home, '.claude', 'plugins', 'cache', 'thedotmack', 'claude-mem');
    const makeVersion = (version: string) => {
      const root = path.join(cacheBase, version);
      writeProbeScripts(root);
      return root;
    };
    // The storm layout: the OLD version dir carries the .orphaned_at stamp and
    // the newest mtime; the NEW version dir is older by mtime. The resolver
    // must pick the new version anyway.
    const oldRoot = makeVersion('13.11.0');
    writeFileSync(path.join(oldRoot, '.orphaned_at'), String(Date.now()));
    const newRoot = makeVersion('13.12.0');
    const past = new Date(Date.now() - 600_000);
    utimesSync(newRoot, past, past);
    try {
      for (const { command } of claudeCommands()) {
        const { status, stdout } = shellEval(command, { HOME: home });
        expect(status).toBe(0);
        expectResolvedPath(stdout, newRoot);
      }
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });

  it('keeps Setup fail-loud when no candidate exists', () => {
    const home = mkdtempSync(path.join(tmpdir(), 'cm-empty-'));
    try {
      const parsed = readJson('plugin/hooks/hooks.json');
      const setupCommand = hookCommandByPath(parsed, 'Setup.0.0')!;
      const setupResult = shellEval(setupCommand, { HOME: home });
      expect(setupResult.status).not.toBe(0);
      expect(setupResult.stderr).toMatch(/claude-mem: .* not found/);
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });

  it('prepends the highest NVM node bin to PATH without login shell (#3190)', () => {
    const home = mkdtempSync(path.join(tmpdir(), 'cm-nvm-only-'));
    installFakeNvmNode(home, '18.20.0');
    const newestBin = installFakeNvmNode(home, '20.11.0');
    const root = path.join(home, 'plugin');
    writeProbeScripts(root);
    const command = hookCommandByPath(readJson('plugin/hooks/hooks.json'), 'Setup.0.0')!;
    try {
      const { status, stdout } = shellEval(command, {
        CLAUDE_PLUGIN_ROOT: root,
        HOME: home,
        PATH: '/usr/bin:/bin',
      });
      expect(status).toBe(0);
      const node = stdout.match(/NODE=(.+)/);
      const nodePath = stdout.match(/PATH=(.+)/);
      expect(node).not.toBeNull();
      expect(nodePath).not.toBeNull();
      expect(normalizeShellPath(node![1])).toBe(normalizeShellPath(path.join(newestBin, 'node')));
      expect(normalizeShellPath(nodePath![1].split(':')[0])).toBe(normalizeShellPath(newestBin));
    } finally {
      rmSync(home, { recursive: true, force: true });
    }
  });
});

describe('Spawn-Contract Templating - Rule B installers bake absolute paths', () => {
  const installerFiles = [
    'src/services/integrations/CursorHooksInstaller.ts',
    'src/services/integrations/WindsurfHooksInstaller.ts',
    'src/services/integrations/McpIntegrations.ts',
    'src/services/integrations/AntigravityCliHooksInstaller.ts',
  ];

  for (const file of installerFiles) {
    it(`${file} emits no raw \${CLAUDE_PLUGIN_ROOT} placeholder`, () => {
      const content = readFileSync(path.join(projectRoot, file), 'utf-8');
      expect(content).not.toMatch(/\$\{CLAUDE_PLUGIN_ROOT\}/);
    });
  }
});