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

28.2 KB
Raw Blame
import path from 'path';
import { homedir } from 'os';
import {
  execFileSync,
  spawnSync,
  type SpawnSyncReturns,
} from 'child_process';
import {
  accessSync,
  constants,
  existsSync,
  mkdirSync,
  readFileSync,
} from 'fs';
import { fileURLToPath } from 'url';
import { logger } from '../../utils/logger.js';
import { findContextBlockRange } from '../../utils/context-injection.js';
import { readJsonFileWithBom, writeJsonFileAtomic, writeTextFileAtomic } from '../../shared/atomic-json.js';
import { expandHome, paths } from '../../shared/paths.js';
import { RUNTIME_SKILLS } from '../../shared/runtime-skills.js';
import { buildSpawnSyncInvocation, lookupWindowsCommandCandidates, type SpawnSyncInvocation } from '../../shared/spawn.js';
import { currentLauncherHostEnvironment, resolveLauncherBinaryPath } from '../../launcher/install-launcher.js';
import { findTomlAssignmentInTable, readTomlBooleanInTable, stripTomlComment, tomlStructuralLines, tomlTableKey } from '../../shared/codex-toml.js';
import { registerCodexUserHooks, removeCodexUserHooks, type CodexUserHooksResult } from './codex-user-hooks.js';

const CODEX_DIR = path.resolve(process.env.CODEX_HOME || path.join(homedir(), '.codex'));
const CODEX_AGENTS_MD_PATH = path.join(CODEX_DIR, 'AGENTS.md');
const CODEX_TRANSCRIPT_WATCH_CONFIG_PATH = paths.transcriptsConfig();
const CODEX_CONFIG_PATH = path.join(CODEX_DIR, 'config.toml');
const MARKETPLACE_NAME = 'claude-mem-local';
const CODEX_PLUGIN_ID = `claude-mem@${MARKETPLACE_NAME}`;
const LEGACY_CODEX_PLUGIN_IDS = ['claude-mem@thedotmack'];
const MIN_CODEX_MARKETPLACE_VERSION = '0.128.0';
const REQUIRED_MARKETPLACE_FILES = [
  path.join('.agents', 'plugins', 'marketplace.json'),
  path.join('plugin', '.codex-plugin', 'plugin.json'),
  path.join('plugin', '.mcp.json'),
  path.join('plugin', 'hooks', 'codex-hooks.json'),
  path.join('plugin', 'skills', RUNTIME_SKILLS.memSearch, 'SKILL.md'),
];
export { readTomlBooleanInTable };

const WINDOWS_CODEX_EXTENSIONS = new Set(['.cmd', '.exe', '.bat', '.com']);
const MACOS_CODEX_BUNDLE_PATHS = [
  '/Applications/ChatGPT.app/Contents/Resources/codex',
  '/Applications/Codex.app/Contents/Resources/codex',
];

export function isExecutableFile(
  candidate: string,
  access: (path: string, mode: number) => void = accessSync,
): boolean {
  try {
    access(candidate, constants.X_OK);
    return true;
  } catch {
    return false;
  }
}

export function isUsableCodexBundle(
  candidate: string,
  probe: typeof spawnSync = spawnSync,
): boolean {
  const result = probe(candidate, ['--version'], {
    stdio: 'ignore',
    windowsHide: true,
    timeout: 5_000,
    killSignal: 'SIGKILL',
  });
  return !result.error && result.status === 0;
}

function commandExists(command: string): boolean {
  if (path.isAbsolute(command)) return isExecutableFile(command);

  try {
    if (process.platform === 'win32') {
      // lookupWindowsCommandCandidates spawns System32's where.exe and drops
      // current-directory hits, so a planted <command>.exe in the project dir
      // cannot pose as an install.
      return lookupWindowsCommandCandidates(command).length > 0;
    }
    execFileSync('which', [command], { stdio: 'ignore' });
    return true;
  } catch {
    // [ANTI-PATTERN IGNORED]: where/which exits non-zero whenever the probed command is absent from PATH; that is the expected negative probe result and commandExists reports it as false.
    return false;
  }
}

function findAncestorWithCodexMarketplace(start: string): string | null {
  let current = path.resolve(start);
  while (true) {
    if (existsSync(path.join(current, '.agents', 'plugins', 'marketplace.json'))) {
      return current;
    }
    const parent = path.dirname(current);
    if (parent === current) return null;
    current = parent;
  }
}

function missingMarketplaceFiles(root: string): string[] {
  return REQUIRED_MARKETPLACE_FILES.filter((entry) => !existsSync(path.join(root, entry)));
}

function assertCodexMarketplaceRoot(root: string): string {
  const resolved = path.resolve(root);
  const missing = missingMarketplaceFiles(resolved);
  if (missing.length > 0) {
    throw new Error(`Codex marketplace root ${resolved} is missing required files: ${missing.join(', ')}`);
  }
  return resolved;
}

function resolvePluginMarketplaceRoot(preferredRoot?: string): string {
  if (preferredRoot) {
    return assertCodexMarketplaceRoot(preferredRoot);
  }

  const candidates = [
    process.env.CLAUDE_PLUGIN_ROOT,
    process.env.PLUGIN_ROOT,
    process.cwd(),
    path.dirname(fileURLToPath(import.meta.url)),
  ].filter((value): value is string => Boolean(value));

  for (const candidate of candidates) {
    const resolved = findAncestorWithCodexMarketplace(candidate);
    if (resolved && missingMarketplaceFiles(resolved).length === 0) return resolved;
  }

  throw new Error('Could not locate a Codex marketplace root with .agents/plugins/marketplace.json and plugin/.codex-plugin/plugin.json. Run npx claude-mem@latest install from the package or repo root.');
}

function lookupCodexOnWindows(): string | null {
  let candidates: string[];
  try {
    candidates = lookupWindowsCommandCandidates('codex');
  } catch (error) {
    const err = error instanceof Error ? error : new Error(String(error));
    logger.warn('WORKER', 'Failed to locate codex via where; falling back to codex.cmd', { command: 'where codex' }, err);
    return null;
  }

  return candidates.find((candidate) => WINDOWS_CODEX_EXTENSIONS.has(path.extname(candidate).toLowerCase()))
    ?? candidates[0]
    ?? null;
}

export function lookupCodexOnMacOS(
  commandInPath: (command: string) => boolean = commandExists,
  candidateAvailable: (candidate: string) => boolean = isUsableCodexBundle,
): string | null {
  if (commandInPath('codex')) return 'codex';
  return MACOS_CODEX_BUNDLE_PATHS.find((candidate) => candidateAvailable(candidate)) ?? null;
}

export function resolveCodexCommand(
  platform: NodeJS.Platform = process.platform,
  windowsLookup: () => string | null = lookupCodexOnWindows,
  macOSLookup: () => string | null = lookupCodexOnMacOS,
): string {
  if (platform === 'win32') return windowsLookup() ?? 'codex.cmd';
  if (platform === 'darwin') return macOSLookup() ?? 'codex';
  return 'codex';
}

export function resolveCodexSpawnInvocation(
  args: string[],
  platform: NodeJS.Platform = process.platform,
  windowsLookup: () => string | null = lookupCodexOnWindows,
  macOSLookup: () => string | null = lookupCodexOnMacOS,
): SpawnSyncInvocation {
  const resolvedCommand = resolveCodexCommand(platform, windowsLookup, macOSLookup);
  return buildSpawnSyncInvocation(resolvedCommand, args, {
    encoding: 'utf-8',
    stdio: ['ignore', 'pipe', 'pipe'],
  }, platform);
}

/**
 * Spawn the `codex` CLI.
 *
 * Issue #2695: on Windows `codex` is installed as `codex.cmd` (a PATH shim).
 * `child_process.spawnSync('codex', args)` without a shell does not consult
 * PATHEXT, so resolve the shim first. Native executables run directly; .cmd
 * and .bat shims use an explicit cmd.exe wrapper without the shell option.
 */
export function codexSpawn(args: string[]): SpawnSyncReturns<string> {
  const invocation = resolveCodexSpawnInvocation(args);
  return spawnSync(invocation.command, invocation.args, invocation.options);
}

type CodexSpawn = (args: string[]) => SpawnSyncReturns<string>;

function runCodex(args: string[], spawn: CodexSpawn = codexSpawn): void {
  const result = spawn(args);
  const output = console;
  const stdout = result.stdout?.trimEnd();
  const stderr = result.stderr?.trimEnd();

  if (stdout) output.log(stdout);
  if (stderr) output.error(stderr);

  if (result.error) {
    throw result.error;
  }
  if (result.status !== 0) {
    const exitCode = result.status ?? 'unknown';
    throw new Error(`codex ${args.join(' ')} failed with exit code ${exitCode}${stderr ? `: ${stderr}` : ''}`);
  }
}

function isMarketplaceDifferentSourceError(error: unknown): boolean {
  const message = error instanceof Error ? error.message : String(error);
  return message.includes(`marketplace '${MARKETPLACE_NAME}' is already added from a different source`)
    || message.includes(`marketplace \`${MARKETPLACE_NAME}\` is already added from a different source`);
}

function registerCodexMarketplace(marketplaceRoot: string, run = runCodex): void {
  try {
    run(['plugin', 'marketplace', 'add', marketplaceRoot]);
    return;
  } catch (error) {
    if (!isMarketplaceDifferentSourceError(error)) {
      throw error instanceof Error ? error : new Error(String(error));
    }
  }

  console.warn(`  Codex marketplace ${MARKETPLACE_NAME} is already registered from another source; replacing it with ${marketplaceRoot}.`);
  run(['plugin', 'marketplace', 'remove', MARKETPLACE_NAME]);
  run(['plugin', 'marketplace', 'add', marketplaceRoot]);
}

export function setTomlBooleanInTable(content: string, header: string, key: string, enabled: boolean): string {
  const booleanLine = `${key} = ${enabled ? 'true' : 'false'}`;
  const lines = content.split('\n');
  const structuralLines = tomlStructuralLines(lines);
  const assignment = findTomlAssignmentInTable(structuralLines, header, key);
  if (assignment) {
    // Preserve a dotted key's parent path; appending a second table would
    // redefine the same key and make an otherwise valid config unreadable.
    lines[assignment.index] = `${lines[assignment.index].slice(0, assignment.keyEnd)}= ${enabled ? 'true' : 'false'}`;
    return lines.join('\n');
  }
  const tableKey = tomlTableKey(header);
  const headerIndex = structuralLines.findIndex((line) => tableKey !== null && tomlTableKey(line) === tableKey);

  if (headerIndex === -1) {
    const trimmed = content.trimEnd();
    return `${trimmed}${trimmed ? '\n\n' : ''}${header}\n${booleanLine}\n`;
  }

  lines.splice(headerIndex + 1, 0, booleanLine);
  return lines.join('\n');
}

export function setTomlPluginEnabled(content: string, pluginId: string, enabled: boolean): string {
  const escapedPluginId = pluginId.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
  return setTomlBooleanInTable(content, `[plugins."${escapedPluginId}"]`, 'enabled', enabled);
}

export function setTomlFeatureEnabled(content: string, featureName: string, enabled: boolean): string {
  return setTomlBooleanInTable(content, '[features]', featureName, enabled);
}

function normalizeTomlHeader(line: string): string | null {
  const match = stripTomlComment(line).trim().match(/^\[([^\]]+)\]\s*$/);
  if (!match) return null;
  return match[1].replace(/\s+/g, '').replace(/"/g, '');
}

/**
 * Read a `[marketplaces.<name>]` entry out of Codex's config.toml.
 *
 * Returns null when the marketplace is not registered. `source` is null when
 * the entry exists but declares no source. Headers and values may carry
 * trailing comments, as in the rest of this file's TOML handling.
 */
export function readRegisteredMarketplace(
  content: string,
  marketplaceName: string,
): { source: string | null; sourceType: string | null } | null {
  const structuralLines = tomlStructuralLines(content.split('\n'));
  const headerIndex = structuralLines.findIndex(
    (line) => normalizeTomlHeader(line) === `marketplaces.${marketplaceName}`,
  );
  if (headerIndex === -1) return null;

  let source: string | null = null;
  let sourceType: string | null = null;
  for (let index = headerIndex + 1; index < structuralLines.length; index += 1) {
    const line = structuralLines[index];
    if (/^\s*\[/.test(line)) break;
    const sourceMatch = line.match(/^\s*source\s*=\s*"(.*)"\s*$/);
    if (sourceMatch) source = sourceMatch[1];
    const typeMatch = line.match(/^\s*source_type\s*=\s*"(.*)"\s*$/);
    if (typeMatch) sourceType = typeMatch[1];
  }
  return { source, sourceType };
}

/**
 * A registered local marketplace whose directory has been deleted or gutted.
 *
 * Only `local` sources are checked: git/npm sources are fetched into a cache,
 * so their `source` is a URL that will never exist on disk and must not be
 * mistaken for a broken path.
 */
export function isStaleLocalMarketplace(
  entry: { source: string | null; sourceType: string | null } | null,
  isUsableRoot: (root: string) => boolean,
): boolean {
  if (!entry?.source) return false;
  if (entry.sourceType !== null && entry.sourceType !== 'local') return false;
  return !isUsableRoot(entry.source);
}

function isUsableMarketplaceRoot(root: string): boolean {
  return existsSync(root) && missingMarketplaceFiles(root).length === 0;
}

/**
 * Codex refuses to load ANY marketplace while one registered source is
 * unreadable: `codex plugin list` hard-errors and every plugin silently stops
 * loading, claude-mem included. Drop a stale registration before re-adding so
 * a moved or deleted checkout self-heals instead of wedging the whole CLI.
 */
function repairStaleMarketplaceRegistration(): void {
  if (!existsSync(CODEX_CONFIG_PATH)) return;

  let entry: ReturnType<typeof readRegisteredMarketplace>;
  try {
    entry = readRegisteredMarketplace(readFileSync(CODEX_CONFIG_PATH, 'utf-8'), MARKETPLACE_NAME);
  } catch (error) {
    logger.warn('WORKER', 'Could not read Codex config while checking for a stale marketplace', {
      error: error instanceof Error ? error.message : String(error),
    });
    return;
  }

  if (!isStaleLocalMarketplace(entry, isUsableMarketplaceRoot)) return;

  console.warn(`  Codex marketplace ${MARKETPLACE_NAME} points at ${entry?.source}, which is missing or incomplete.`);
  console.warn('  Removing the stale registration so Codex can load plugins again.');
  runCodex(['plugin', 'marketplace', 'remove', MARKETPLACE_NAME]);
}

function isLegacyMcpSearchHeader(normalizedHeader: string | null): boolean {
  return normalizedHeader === 'mcp_servers.mcp-search';
}

function isLegacyMcpSearchChildHeader(normalizedHeader: string | null): boolean {
  return typeof normalizedHeader === 'string' && normalizedHeader.startsWith('mcp_servers.mcp-search.');
}

function isClaudeMemMcpSearchBlock(block: string): boolean {
  return /claude-mem/.test(block);
}

export function removeLegacyCodexMcpSearchConfig(content: string): string {
  const lines = content.split('\n');
  const structuralLines = tomlStructuralLines(lines);
  const blocks: Array<{ header: string | null; text: string }> = [];
  let currentHeader: string | null = null;
  let currentLines: string[] = [];

  for (const [index, line] of lines.entries()) {
    const header = normalizeTomlHeader(structuralLines[index]);
    if (header !== null) {
      blocks.push({ header: currentHeader, text: currentLines.join('\n') });
      currentHeader = header;
      currentLines = [line];
    } else {
      currentLines.push(line);
    }
  }
  blocks.push({ header: currentHeader, text: currentLines.join('\n') });

  const removeLegacyMcpSearch = blocks.some(
    (block) => isLegacyMcpSearchHeader(block.header) && isClaudeMemMcpSearchBlock(block.text),
  );
  if (!removeLegacyMcpSearch) return content;

  const kept = blocks.filter((block) =>
    !isLegacyMcpSearchHeader(block.header) && !isLegacyMcpSearchChildHeader(block.header)
  );
  // The stale claude-mem-owned server can have tool child tables; remove the
  // whole subtree so Codex falls back to the plugin-managed MCP declaration.
  return kept.map((block) => block.text).join('\n').replace(/^\n+/, '').replace(/\n{3,}/g, '\n\n');
}

function writeCodexPluginConfig(enabled: boolean, configPath = CODEX_CONFIG_PATH): boolean {
  if (!enabled && !existsSync(configPath)) return false;
  mkdirSync(path.dirname(configPath), { recursive: true });
  const current = existsSync(configPath) ? readFileSync(configPath, 'utf-8') : '';
  let next = current;

  if (enabled) {
    next = setTomlFeatureEnabled(next, 'hooks', true);
    next = removeLegacyCodexMcpSearchConfig(next);
  }
  for (const legacyPluginId of LEGACY_CODEX_PLUGIN_IDS) {
    next = setTomlPluginEnabled(next, legacyPluginId, false);
  }
  next = setTomlPluginEnabled(next, CODEX_PLUGIN_ID, enabled);

  if (next === current) return false;
  writeTextFileAtomic(configPath, next);
  return true;
}

function enableCodexPluginConfig(): void {
  const changed = writeCodexPluginConfig(true);
  console.log(`  Enabled Codex plugin: ${CODEX_PLUGIN_ID}${changed ? '' : ' (already enabled)'}`);
}

function disableCodexPluginConfig(): void {
  const changed = writeCodexPluginConfig(false);
  console.log(`  Disabled Codex plugin: ${CODEX_PLUGIN_ID}${changed ? '' : ' (already disabled)'}`);
}

function extractSemver(value: string): string | null {
  return value.match(/\d+\.\d+\.\d+/)?.[0] ?? null;
}

function assertCodexMarketplaceSupported(spawn: CodexSpawn = codexSpawn): void {
  const result = spawn(['--version']);
  const output = `${result.stdout ?? ''}\n${result.stderr ?? ''}`.trim();

  if (result.error) {
    throw result.error;
  }
  if (result.status !== 0) {
    console.warn(`  Could not determine Codex CLI version. Continuing; plugin marketplace support requires ${MIN_CODEX_MARKETPLACE_VERSION} or newer.${output ? `\n${output}` : ''}`);
    return;
  }

  const version = extractSemver(output);
  if (!version) {
    console.warn(`  Could not parse Codex CLI version from "${output || '<empty>'}". Continuing; plugin marketplace support requires ${MIN_CODEX_MARKETPLACE_VERSION} or newer.`);
    return;
  }

  if (version.localeCompare(MIN_CODEX_MARKETPLACE_VERSION, undefined, { numeric: true }) < 0) {
    throw new Error(`Codex CLI ${version} is too old for plugin marketplace support. Update Codex CLI to ${MIN_CODEX_MARKETPLACE_VERSION} or newer, then run: npx claude-mem@latest install`);
  }
}

function removeCodexAgentsMdContext(): boolean {
  if (!existsSync(CODEX_AGENTS_MD_PATH)) return true;

  try {
    readAndStripContextTags();
    return true;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    logger.warn('WORKER', 'Failed to clean AGENTS.md context', { error: message });
    return false;
  }
}

export function readAndStripContextTags(agentsMdPath = CODEX_AGENTS_MD_PATH): void {
  const content = readFileSync(agentsMdPath, 'utf-8');

  const block = findContextBlockRange(content);
  if (!block) return;

  const before = content.substring(0, block.start).replace(/\n+$/, '');
  const after = content.substring(block.end).replace(/^\n+/, '');
  const finalContent = (before + (after ? '\n\n' + after : '')).trim();

  if (finalContent) {
    writeTextFileAtomic(agentsMdPath, finalContent + '\n');
  } else {
    writeTextFileAtomic(agentsMdPath, '');
  }

  console.log(`  Removed legacy global context from ${agentsMdPath}`);
}

const cleanupLegacyCodexAgentsMdContext = removeCodexAgentsMdContext;

function isRecord(value: unknown): value is Record<string, unknown> {
  return value !== null && typeof value === 'object' && !Array.isArray(value);
}

function isCodexTranscriptWatch(watch: Record<string, unknown>): boolean {
  return watch.name === 'codex' || watch.schema === 'codex';
}

function isLegacyCodexAgentsContext(context: Record<string, unknown>): boolean {
  if (context.mode !== 'agents') return false;

  const updateOn = context.updateOn;
  const hasLegacyUpdateOn = Array.isArray(updateOn)
    && updateOn.length === 2
    && updateOn.includes('session_start')
    && updateOn.includes('session_end');
  if (!hasLegacyUpdateOn) return false;

  if (context.path === undefined) return true;
  return typeof context.path === 'string'
    && path.resolve(expandHome(context.path)) === CODEX_AGENTS_MD_PATH;
}

function disableCodexTranscriptAgentsContext(): boolean {
  if (!existsSync(CODEX_TRANSCRIPT_WATCH_CONFIG_PATH)) return true;

  try {
    stripLegacyTranscriptWatchContexts();
    return true;
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    logger.warn('WORKER', 'Failed to disable Codex transcript AGENTS.md context', { error: message });
    return false;
  }
}

export function stripLegacyTranscriptWatchContexts(configPath = CODEX_TRANSCRIPT_WATCH_CONFIG_PATH): void {
  const parsed = readJsonFileWithBom<unknown>(configPath);
  if (!isRecord(parsed) || !Array.isArray(parsed.watches)) return;

  let changed = false;
  for (const watch of parsed.watches) {
    if (!isRecord(watch) || !isCodexTranscriptWatch(watch)) continue;
    if (!isRecord(watch.context) || !isLegacyCodexAgentsContext(watch.context)) continue;
    delete watch.context;
    changed = true;
  }

  if (changed) {
    writeJsonFileAtomic(configPath, parsed);
    console.log(`  Disabled legacy Codex transcript AGENTS.md context in ${configPath}`);
  }
}

const cleanupLegacyCodexTranscriptAgentsContext = disableCodexTranscriptAgentsContext;

/**
 * Register claude-mem's hooks in the home's own hooks.json, not in the plugin
 * bundle: Codex re-approves a bundled hook after every plugin update, and a
 * user-level hook only when its declaration changes (see codex-user-hooks.ts).
 * `dryRun` checks that the existing file can be merged without writing it.
 */
function registerCodexHooksForHome(
  marketplaceRoot: string,
  codexHome: string,
  options: { dryRun?: boolean; launcherPath?: string } = {},
): CodexUserHooksResult {
  return registerCodexUserHooks({
    codexHome,
    hookDefinitionsPath: path.join(marketplaceRoot, 'plugin', 'hooks', 'codex-hooks.json'),
    launcherPath: options.launcherPath ?? resolveLauncherBinaryPath(currentLauncherHostEnvironment()),
    dryRun: options.dryRun,
  });
}

export async function installCodexCli(marketplaceRootOverride?: string): Promise<number> {
  console.log('\nInstalling Claude-Mem for Codex CLI (native hooks)...\n');

  if (!commandExists(resolveCodexCommand())) {
    console.error('Codex CLI was not found on PATH.');
    console.error('Install Codex, then run: npx claude-mem@latest install');
    return 1;
  }

  try {
    return performCodexInstall(marketplaceRootOverride);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error(`\nInstallation failed: ${message}`);
    return 1;
  }
}

/** Install into the shared home used by a T3 Code provider, without changing process.env. */
export function installCodexPluginForHome(options: {
  marketplaceRoot: string;
  homePath: string;
  spawn: CodexSpawn;
  /** Defaults to the on-PATH claude-mem launcher. */
  launcherPath?: string;
}): void {
  const root = assertCodexMarketplaceRoot(options.marketplaceRoot);
  assertCodexMarketplaceSupported(options.spawn);
  // Refuse an unreadable hooks.json before changing anything in this home.
  registerCodexHooksForHome(root, options.homePath, { dryRun: true, launcherPath: options.launcherPath });
  const run = (args: string[]) => runCodex(args, options.spawn);
  registerCodexMarketplace(root, run);
  // The refreshed plugin copy bundles no hooks, so adding it first means the
  // user-level hooks written next are the only registration.
  run(['plugin', 'add', CODEX_PLUGIN_ID]);
  writeCodexPluginConfig(true, path.join(options.homePath, 'config.toml'));
  registerCodexHooksForHome(root, options.homePath, { launcherPath: options.launcherPath });
}

export function disableCodexPluginForHome(homePath: string): void {
  writeCodexPluginConfig(false, path.join(homePath, 'config.toml'));
  removeCodexUserHooks(homePath);
}

function performCodexInstall(marketplaceRootOverride?: string): number {
  assertCodexMarketplaceSupported();
  const marketplaceRoot = resolvePluginMarketplaceRoot(marketplaceRootOverride);

  // Refuse an unreadable hooks.json before changing anything in Codex's home.
  registerCodexHooksForHome(marketplaceRoot, CODEX_DIR, { dryRun: true });

  console.log(`  Registering Codex plugin marketplace: ${marketplaceRoot}`);
  repairStaleMarketplaceRegistration();
  registerCodexMarketplace(marketplaceRoot);
  enableCodexPluginConfig();
  // The refreshed plugin copy bundles no hooks, so adding it first means the
  // user-level hooks written next are the only registration.
  runCodex(['plugin', 'add', CODEX_PLUGIN_ID]);
  console.log('  Installed Codex plugin cache.');
  const hooks = registerCodexHooksForHome(marketplaceRoot, CODEX_DIR);
  console.log(`  Registered ${hooks.hookCount} claude-mem hooks in ${hooks.hooksPath}${hooks.changed ? '' : ' (already registered)'}`);
  const launcherPath = resolveLauncherBinaryPath(currentLauncherHostEnvironment());
  if (!existsSync(launcherPath)) {
    console.warn(`  The claude-mem launcher is not at ${launcherPath} yet. Codex hooks run through it; run: npx claude-mem@latest install`);
  }
  if (!cleanupLegacyCodexAgentsMdContext()) {
    console.warn(`  Native Codex hooks registered, but failed to remove legacy AGENTS.md context from ${CODEX_AGENTS_MD_PATH}.`);
  }
  if (!cleanupLegacyCodexTranscriptAgentsContext()) {
    console.warn(`  Native Codex hooks registered, but failed to disable legacy transcript AGENTS.md context in ${CODEX_TRANSCRIPT_WATCH_CONFIG_PATH}.`);
  }

  if (!verifyCodexPluginLoaded()) {
    console.error(`
Installation failed: Codex does not list ${CODEX_PLUGIN_ID}.

Codex will not load the plugin, so no memory context will be injected.
Inspect the plugin and marketplace state with:
  codex plugin list
`);
    return 1;
  }

  console.log(`
Installation complete!

Codex marketplace: ${MARKETPLACE_NAME}
Plugin source:     ${marketplaceRoot}

Next steps:
  1. Open Codex CLI in your project
  2. Review and trust the ${hooks.hookCount} claude-mem hooks when Codex prompts you, or with /hooks
  3. Restart sessions opened before trusting the hooks

The hooks live in ${hooks.hooksPath}, so this approval stays valid
across claude-mem updates. Codex asks again only when a hook's own
definition changes or another tool's hook is removed ahead of it.

For a fresh setup, the supported entry point is:
  npx claude-mem@latest install
`);
  return 0;
}

/**
 * Surface a failed install instead of reporting success into a void: a plugin
 * that Codex cannot list will silently never inject context.
 *
 * Returns false only when Codex positively reported the plugin as absent. An
 * unusable `plugin list` (spawn error, non-zero exit) means the state is
 * unknown, not broken; the install steps themselves succeeded, so that warns
 * and continues rather than failing a good install on an unrelated CLI hiccup.
 */
export function verifyCodexPluginLoaded(spawn: CodexSpawn = codexSpawn): boolean {
  const result = spawn(['plugin', 'list']);
  const output = `${result.stdout ?? ''}\n${result.stderr ?? ''}`.trim();

  if (result.error || result.status !== 0) {
    console.warn('  Could not verify the Codex plugin list. Check with: codex plugin list');
    if (output) console.warn(`  ${output.split('\n')[0]}`);
    return true;
  }

  if (!output.includes(CODEX_PLUGIN_ID)) {
    console.error(`  Codex did not list ${CODEX_PLUGIN_ID} after install.`);
    return false;
  }

  console.log(`  Verified Codex lists ${CODEX_PLUGIN_ID}.`);
  return true;
}

export function uninstallCodexCli(): number {
  console.log('\nUninstalling Claude-Mem Codex CLI integration...\n');

  let failed = false;

  try {
    disableCodexPluginConfig();
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error(`\nCodex plugin config update failed: ${message}`);
    failed = true;
  }

  try {
    const removed = removeCodexUserHooks(CODEX_DIR);
    console.log(`  Removed claude-mem hooks from ${removed.hooksPath}${removed.changed ? '' : ' (none registered)'}`);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error(`\nCodex hooks removal failed: ${message}`);
    failed = true;
  }

  try {
    if (commandExists(resolveCodexCommand())) {
      runCodex(['plugin', 'marketplace', 'remove', MARKETPLACE_NAME]);
    } else {
      console.log('  Codex CLI not found; skipping marketplace removal.');
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error(`\nCodex marketplace removal failed: ${message}`);
    failed = true;
  }

  try {
    if (!cleanupLegacyCodexAgentsMdContext()) {
      console.error(`\nFailed to remove legacy AGENTS.md context from ${CODEX_AGENTS_MD_PATH}.`);
      failed = true;
    }
    if (!cleanupLegacyCodexTranscriptAgentsContext()) {
      console.error(`\nFailed to disable legacy transcript AGENTS.md context in ${CODEX_TRANSCRIPT_WATCH_CONFIG_PATH}.`);
      failed = true;
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.error(`\nLegacy context cleanup failed: ${message}`);
    failed = true;
  }

  if (failed) {
    console.error('\nUninstallation completed with errors.');
    return 1;
  }

  console.log('\nUninstallation complete!');
  console.log('Restart Codex CLI to apply changes.\n');

  return 0;
}