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

63.5 KB
Raw Blame
#!/usr/bin/env node

import { deepSearchBuildPlugin } from './deep-search-build.js';
import { build } from 'esbuild';
import fs from 'fs';
import path from 'path';
import vm from 'node:vm';
import { isDeepStrictEqual } from 'node:util';
import { fileURLToPath } from 'url';
import { allowScriptsMap } from './postinstall-allowlist.js';
import { refusedEventsHooked } from './code-mode-refused-events.js';
import { OPENCODE_PLUGIN_BUILD_OPTIONS } from './opencode-plugin-build-options.js';
import { preparePiExtensionBuild, preflightDshAttribution, DSH_PLUGIN_BUILD_OPTIONS } from './harness-plugin-build-options.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

// Map every __dirname/__filename in the bundled body to runtime-computed
// globals, applied by esbuild BEFORE minification. Any absolute build-machine
// path a dependency would otherwise inline becomes a reference to the banner
// values below, so nothing needs to be rewritten after emit. This replaces the
// old post-build regex rewrite (stripHardcodedDirname), which swept a 2.6 MB
// minified bundle and could delete a top-level declaration — the worker then
// died with an unhandled "ReferenceError: <name> is not defined". See
// assertBundleIntegrity.
const DIRNAME_DEFINE = {
  '__dirname': '__CM_DIRNAME__',
  '__filename': '__CM_FILENAME__',
};

// Declares the globals DIRNAME_DEFINE maps to. `define` never rewrites banner
// text, so these lines still read Node's native __dirname/__filename (present
// in every CJS module) and fall back to argv[1] when the bundle is the process
// entrypoint under Bun.
const DIRNAME_BANNER = [
  'var __CM_FILENAME__ = typeof __filename !== "undefined" ? __filename : require("node:path").resolve(process.argv[1] || "");',
  'var __CM_DIRNAME__ = typeof __dirname !== "undefined" ? __dirname : require("node:path").dirname(__CM_FILENAME__);',
];

// posthog-node >=5.56 lazily import()s the optional OpenTelemetry API for trace ids
// and swallows the failure when it is absent, so every bundle that includes the
// telemetry client must leave it unresolved instead of failing the build.
const POSTHOG_OPTIONAL_IMPORTS = ['@opentelemetry/api'];

// Emit an external source map (names only, no inlined source text) next to each
// bundle. Bun and Node symbolicate stack traces against the adjacent .map, so a
// worker crash names the real symbol instead of a two-letter minified id.
const SOURCEMAP_OPTS = { sourcemap: true, sourcesContent: false };

// A bundle must parse and must not carry an absolute build path. esbuild emits a
// closed, self-consistent module graph and we now ship it verbatim, so either
// failure means a real regression — fail the build rather than ship a bundle
// that throws at load or leaks the builder's filesystem layout.
function assertBundleIntegrity(filePath) {
  const content = fs.readFileSync(filePath, 'utf-8');
  try {
    new vm.Script(content.replace(/^#!.*\n/, ''), { filename: filePath });
  } catch (err) {
    throw new Error(`${filePath} does not parse after build (${err.message}). Refusing to ship a corrupt bundle.`);
  }
  // esbuild's ESM __dirname inlining (the leak the old rewrite existed for)
  // emits the absolute directory of a bundled module — always under the
  // checkout's node_modules/ or src/. Match those exact prefixes, not any
  // substring of the checkout path, so a legitimate runtime path that merely
  // shares an ancestor of the build dir (e.g. Bun's /home/linuxbrew/.bun/bin/bun
  // when building from /home) is never misread as a leak.
  const buildDir = process.cwd();
  const leaked = ['node_modules', 'src']
    .map((dir) => buildDir + path.sep + dir + path.sep)
    .find((prefix) => content.includes(prefix));
  if (leaked) {
    throw new Error(
      `${filePath} inlined the absolute build path ${leaked}…: a __dirname/__filename literal leaked. Check the esbuild \`define\` mapping.`
    );
  }
}

const WORKER_SERVICE = {
  name: 'worker-service',
  source: 'src/services/worker-service.ts'
};

// Hook-only bundle: every agent hook is a short-lived process, and parsing the
// whole worker bundle for it costs ~0.3 s and ~120 MB. The launcher and
// bun-runner.js run this file for `hook` when it exists and fall back to
// worker-service.cjs otherwise. Keep src/cli/hook-entry.ts free of worker,
// server and provider imports (the build asserts a size budget below).
const HOOK_SERVICE = {
  name: 'hook-service',
  source: 'src/cli/hook-entry.ts'
};

const SERVER_SERVICE = {
  name: 'server-service',
  source: 'src/server/runtime/ServerService.ts'
};

const MCP_SERVER = {
  name: 'mcp-server',
  source: 'src/servers/mcp-server.ts'
};

const CONTEXT_GENERATOR = {
  name: 'context-generator',
  source: 'src/services/context-generator.ts'
};

const CONTEXT_READ_WORKER = {
  name: 'context-read-worker',
  source: 'src/services/context/context-read-worker.ts'
};

const WORK_VIEW_READ_WORKER = {
  name: 'work-view-read-worker',
  source: 'src/services/work-view/work-view-read-worker.ts'
};

const TRANSCRIPT_WATCHER = {
  name: 'transcript-watcher',
  source: 'src/services/transcripts/transcript-watcher-entry.ts'
};

// The on-PATH `claude-mem` hook launcher (plan-17 #3605). The installer compiles
// this bundle with `bun build --compile`; it must stay version-stable, so it
// imports nothing from src/services, src/cli/handlers or src/shared/worker-utils.
const HOOK_LAUNCHER = {
  name: 'claude-mem-launcher',
  source: 'src/launcher/claude-mem-launcher.ts'
};

// SessionStart self-heal that compiles HOOK_LAUNCHER onto PATH when it is
// missing or stale (plan-17 #3605, Phase 3). Runs under plain `node`, so it
// must stay free of bun:sqlite and worker imports.
const ENSURE_LAUNCHER = {
  name: 'ensure-launcher',
  source: 'src/launcher/ensure-launcher.ts'
};

// claude-mem's Claude Code hooks module, named by `modules` in
// plugin/hooks/hooks.json. Claude Code allows a plugin one such module, so it
// registers every claude-mem mod (src/mods/): auto-clear and the session-start card.
const HOOKS_MODULE = {
  source: 'src/mods/hooks-module.ts',
  outfile: 'plugin/hooks/hooks-module.js',
  // The same file as hooks.json names it: a path relative to hooks.json.
  hooksJsonModules: ['./hooks-module.js']
};

// A hooks module runs with no Node: no require, no node: imports, and it must
// export `register`. vm.Script cannot parse an ES module, so check the text.
function assertModBundle(filePath) {
  const content = fs.readFileSync(filePath, 'utf-8');
  if (!/^export\s*\{[^}]*\bregister\b[^}]*\}/m.test(content) && !/^export\s+(const|function)\s+register\b/m.test(content)) {
    throw new Error(`${filePath} does not export register. Claude Code would load no hooks from it.`);
  }
  const nodeImport = content.match(/\brequire\(|from\s+["']node:|from\s+["'](fs|os|path|child_process)["']/);
  if (nodeImport) {
    throw new Error(`${filePath} reaches for Node (${nodeImport[0]}). A hooks module has no Node APIs: keep src/mods/ free of Node imports.`);
  }
  const refused = refusedEventsHooked(content);
  if (refused.length > 0) {
    throw new Error(
      `${filePath} hooks ${refused.join(', ')}. Claude Code's Code Mode refuses to start when an enabled plugin's hooks module hooks any event listed in scripts/code-mode-refused-events.js, `
      + 'so this bundle would turn Code Mode off for all of claude-mem. Hook an event outside that list (session.append for tool results).'
    );
  }
}

/**
 * Rule A canonical-template manifest: maps each host-managed config file's
 * command string to the buildShellCommand() options that generate it, and each
 * Claude Code runtime hook in plugin/hooks/hooks.json to its full exec-form
 * entry (buildExecHook; `execEntries`). The
 * build asserts the hand-maintained files still match the generator output so
 * the defensive shell prelude can't drift between the three files (issues
 * #1215, #1533). See src/build/hook-shell-template.ts and CLAUDE.md →
 * "Spawn-Contract Resolution".
 */
// Claude Code's UserPromptSubmit timeout (seconds). It must stay above the
// session-init budget (HOOK_TIMEOUTS.SESSION_INIT_REQUEST, 10 s by default;
// CLAUDE_MEM_SESSION_INIT_TIMEOUT_MS allows up to 14 s) plus hook startup (#3434).
const SESSION_INIT_HOOK_TIMEOUT_SECONDS = 15;

// SessionStart self-heal timeout (seconds). The hook is synchronous so its
// failure systemMessage reaches the user, so this bounds session start in the
// worst case: the installed launcher's --version probe (10 s), the Bun lookup
// (`bun --version`, normally well under 1 s), `bun build --compile` (120 s),
// the compiled launcher's --version probe (10 s) and the Windows PowerShell
// user-PATH write (30 s) back to back = 170 s plus node startup
// (src/launcher/install-launcher.ts). When the launcher is current it is one
// --version spawn and returns in milliseconds.
const ENSURE_LAUNCHER_HOOK_TIMEOUT_SECONDS = 180;

// The only shell-form entry allowed in plugin/hooks/hooks.json. Setup fires
// only on `claude --init` / `--maintenance` (SPIKE item 8), never at runtime.
const SHELL_FORM_HOOK_EVENTS = new Set(['Setup']);

// Claude Code's PreToolUse Read timeout (seconds). The hook is synchronous so
// the File Read Gate can deny a whole-file Read, which makes every Read wait on
// it: bounded well under the old 60 s, and above the 3 s worker budget
// (FILE_CONTEXT_WORKER_BUDGET_MS in src/cli/handlers/file-context.ts) plus hook
// startup.
const FILE_CONTEXT_HOOK_TIMEOUT_SECONDS = 15;

// PreToolUse matcher (#4596, #4549): Read for the File Read Gate / file
// timeline (read_file is Grok Build's read tool), plus the tools whose calls the memory-search handler inspects.
const PRE_TOOL_USE_MATCHER = 'Read|^read_file$|^Bash$|^Grep$|^Glob$|^memory_search$|^memory$|^mcp__.+__memory_search$';

export function shellTemplateManifest(buildShellCommand, buildCodexWindowsCommand, buildExecHook, buildEnsureLauncherExecHook) {
  const ccTrailing = (...tail) => [
    'node', '"$_P/scripts/bun-runner.js"', '"$_P/scripts/worker-service.cjs"', ...tail,
  ];
  // Claude Code runtime hooks are exec form (plan-17 #3605): the full entry
  // is canonical, so `--write-shell-templates` can (re)generate it and the
  // verifier rejects any hand edit, including a re-added `shell` key.
  const claudeExecHook = (workerServiceArguments, entryOptions, groupMatcher) => ({
    groupMatcher,
    entry: { type: 'command', ...buildExecHook(workerServiceArguments), ...entryOptions },
  });
  const codexHook = (tail) => 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' },
    // Codex's own plugin copy carries the scripts but never `node_modules`
    // (the CLI rebuilds that folder on every `codex plugin add`), so a hook
    // resolving to it dies on its first import. Require the host-injected
    // root to have its dependencies; without them the resolver falls back to
    // the installer-prepared copies (#4763).
    requireDependencies: true,
  });
  const codexHookPair = (tail, entryOptions = {}) => ({
    command: codexHook(tail),
    commandWindows: buildCodexWindowsCommand(tail, { requireDependencies: true }),
    ...entryOptions,
  });

  return {
    'plugin/hooks/hooks.json': {
      kind: 'hooks',
      commands: {
        'Setup.0.0': buildShellCommand({
          host: 'claude-code-setup', requireFile: 'version-check.js',
          trailingCommand: ['node', '"$_P/scripts/version-check.js"'],
          notFoundMessage: 'claude-mem: version-check.js not found',
        }),
      },
      execEntries: {
        // `start` already emits its own single, valid status JSON via
        // buildStatusOutput ({"continue":true,"status":"ready","suppressOutput":true}).
        // Never append a second stdout document to it: two concatenated JSON
        // objects are invalid, so Claude Code would dump the raw text at the top
        // of every session.
        'SessionStart.0.0': claudeExecHook(['start'], { timeout: 60, async: true }, 'startup|resume|clear|compact'),
        // No `resume`: a resumed session already has its timeline (#4423).
        'SessionStart.1.0': claudeExecHook(['hook', 'claude-code', 'context'], { timeout: 60 }, 'startup|clear|compact'),
        // Self-heal for marketplace-only installs (SPIKE Decision 1): compile the
        // launcher onto PATH when it is missing or stale. Runs on all
        // SessionStart sources so `/plugin` update + `/reload-plugins` followed
        // by `/clear`, `/compact`, or `resume` still self-heals (#4969).
        // Synchronous (no `async`): Claude Code shows a sync hook's
        // systemMessage to the user, which is how a failed self-heal is reported.
        'SessionStart.2.0': {
          groupMatcher: 'startup|resume|clear|compact',
          entry: { type: 'command', ...buildEnsureLauncherExecHook(), timeout: ENSURE_LAUNCHER_HOOK_TIMEOUT_SECONDS },
        },
        'UserPromptSubmit.0.0': claudeExecHook(['hook', 'claude-code', 'session-init'], { timeout: SESSION_INIT_HOOK_TIMEOUT_SECONDS }),
        'PostToolUse.0.0': claudeExecHook(['hook', 'claude-code', 'observation'], { timeout: 120, async: true }, '*'),
        // A tool call that fails (e.g. Bash exiting non-zero) is delivered here
        // instead of PostToolUse, so without it memory never sees a failed attempt.
        'PostToolUseFailure.0.0': claudeExecHook(['hook', 'claude-code', 'observation'], { timeout: 120, async: true }, '*'),
        // Synchronous so the File Read Gate can deny a whole-file Read.
        'PreToolUse.0.0': claudeExecHook(['hook', 'claude-code', 'file-context'], { timeout: FILE_CONTEXT_HOOK_TIMEOUT_SECONDS }, PRE_TOOL_USE_MATCHER),
        'Stop.0.0': claudeExecHook(['hook', 'claude-code', 'summarize'], { timeout: 120, async: true }),
        // Records that a subagent finished, so My Work stops showing it as working.
        'SubagentStop.0.0': claudeExecHook(['hook', 'claude-code', 'subagent-stop'], { timeout: 30, async: true }),
        'SessionEnd.0.0': claudeExecHook(['hook', 'claude-code', 'session-end'], { async: true }),
      },
    },
    'plugin/hooks/codex-hooks.json': {
      kind: 'hooks',
      commands: {
        'SessionStart.0.0': codexHookPair(['hook', 'codex', 'context']),
        'UserPromptSubmit.0.0': codexHookPair(['hook', 'codex', 'session-init']),
        'PreToolUse.0.0': codexHookPair(['hook', 'codex', 'file-context']),
        // Observation capture stays synchronous so a delayed event cannot cross
        // turn boundaries. Why 5 s: the hook must fit wrapper startup, bundle
        // load, the 2 s server attempt (SERVER_OBSERVATION_TIMEOUT_MS in
        // src/cli/handlers/observation.ts) and the local spool write. Measured
        // on an Apple Silicon Mac (2026-10-25, worker runtime, spool path):
        // ~0.25-0.29 s warm, ~0.46 s on the first run. So 5 s leaves ~2.5 s of
        // headroom after the server attempt. Windows (commandWindows) cold
        // start was not measured. Change both values together.
        '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']),
      },
    },
    'plugin/.mcp.json': {
      kind: 'mcp',
      command: buildShellCommand({
        // The mcp Node launcher derives its module target from requireFile, so
        // no trailingCommand is needed (it is ignored for this host).
        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, dottedPath) {
  const [event, groupIdx, hookIdx] = dottedPath.split('.');
  return parsed.hooks?.[event]?.[Number(groupIdx)]?.hooks?.[Number(hookIdx)] ?? null;
}

/**
 * Compare one exec-form hook entry (and its group matcher) against the
 * manifest. In write mode a mismatching entry is replaced with the canonical
 * one; a missing group or entry is never created (add it to hooks.json by
 * hand, then regenerate). Returns true when the parsed file was modified.
 */
function applyCanonicalExecEntry(parsed, dottedPath, expected, filePath, writeMode) {
  const [event, groupIndexText, hookIndexText] = dottedPath.split('.');
  const group = parsed.hooks?.[event]?.[Number(groupIndexText)] ?? null;
  const entry = group?.hooks?.[Number(hookIndexText)] ?? null;
  const matcherMatches = group !== null && group.matcher === expected.groupMatcher;
  if (entry !== null && matcherMatches && isDeepStrictEqual(entry, expected.entry)) return false;

  if (!writeMode || entry === null) {
    throw new Error(
      `Hand-edited hook entry detected in ${filePath} (${dottedPath}). It no longer matches the exec-form manifest in scripts/build-hooks.js. ` +
      `Regenerate via \`node scripts/build-hooks.js --write-shell-templates\` after an intentional generator change.`
    );
  }
  if (expected.groupMatcher === undefined) delete group.matcher;
  else group.matcher = expected.groupMatcher;
  group.hooks[Number(hookIndexText)] = structuredClone(expected.entry);
  return true;
}

/**
 * Rule A for Claude Code runtime hooks (plan-17 #3605): every entry outside
 * Setup must be shell-free exec form. A `shell` key, a missing `args` array, or
 * any command other than the on-PATH `claude-mem` launcher (or the single
 * `node …/ensure-launcher.cjs` self-heal), or a `claude-mem` entry whose args
 * are not in the manifest, brings back the bash preamble and the
 * Windows console flash (#3559, #3521, #3396).
 */
export function verifyClaudeCodeRuntimeHooksAreExecForm(parsed, execEntries, ensureLauncherExecHook, filePath) {
  const manifestLauncherArgs = Object.values(execEntries)
    .map(({ entry }) => entry)
    .filter((entry) => entry.command === 'claude-mem')
    .map((entry) => entry.args);
  for (const [event, groups] of Object.entries(parsed.hooks ?? {})) {
    if (SHELL_FORM_HOOK_EVENTS.has(event)) continue;
    groups.forEach((group, groupIndex) => {
      (group.hooks ?? []).forEach((entry, hookIndex) => {
        const location = `${event}.${groupIndex}.${hookIndex}`;
        const hasShell = Object.prototype.hasOwnProperty.call(entry, 'shell');
        const hasArgs = Array.isArray(entry.args);
        const isLauncher = entry.command === 'claude-mem';
        const isManifestLauncher = isLauncher && manifestLauncherArgs
          .some((launcherArgs) => isDeepStrictEqual(entry.args, launcherArgs));
        const isEnsureLauncher = entry.command === ensureLauncherExecHook.command
          && isDeepStrictEqual(entry.args, ensureLauncherExecHook.args);
        if (hasShell || !hasArgs || !(isManifestLauncher || isEnsureLauncher)) {
          const offendingDetail = hasShell ? `shell=${JSON.stringify(entry.shell)}`
            : !hasArgs ? 'no args array'
              : isLauncher ? `claude-mem args ${JSON.stringify(entry.args)} that are not in the manifest`
                : `command=${JSON.stringify(entry.command)}`;
          throw new Error(
            `Claude Code runtime hook must be exec form (command+args, no shell): ${filePath} (${location}) has ${offendingDetail}.`
          );
        }
      });
    });
  }
}

async function verifyShellTemplateCanonical() {
  console.log('\n📋 Verifying Rule A shell templates match the canonical generator...');

  // Compile src/build/hook-shell-template.ts in-memory and import it. The build
  // runs under Node, which can't import .ts directly, so we bundle to ESM and
  // load via a data: URL.
  const bundled = await build({
    entryPoints: ['src/build/hook-shell-template.ts'],
    bundle: true,
    platform: 'node',
    format: 'esm',
    write: false,
    logLevel: 'error',
  });
  const moduleSource = bundled.outputFiles[0].text;
  const dataUrl = 'data:text/javascript;base64,' + Buffer.from(moduleSource).toString('base64');
  const { buildShellCommand, buildCodexWindowsCommand, buildExecHook, buildEnsureLauncherExecHook } = await import(dataUrl);

  const manifest = shellTemplateManifest(buildShellCommand, buildCodexWindowsCommand, buildExecHook, buildEnsureLauncherExecHook);

  // The regeneration mode the mismatch errors point at: after an intentional
  // generator change, rewrite the committed launcher strings from the same
  // manifest the verifier checks, so the two can never drift.
  const writeMode = process.argv.includes('--write-shell-templates');

  for (const [filePath, spec] of Object.entries(manifest)) {
    const parsed = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
    let dirty = false;
    if (spec.kind === 'mcp') {
      const actual = parsed.mcpServers?.['mcp-search']?.args?.[1] ?? '';
      if (actual !== spec.command) {
        if (!writeMode) {
          throw new Error(
            `Hand-edited shell string detected in ${filePath} (mcp-search). It no longer matches src/build/hook-shell-template.ts. ` +
            `Regenerate via \`node scripts/build-hooks.js --write-shell-templates\` after an intentional generator change.`
          );
        }
        parsed.mcpServers['mcp-search'].args[1] = spec.command;
        dirty = true;
      }
    } else {
      for (const [dottedPath, expected] of Object.entries(spec.commands)) {
        const entry = hookEntryByPath(parsed, dottedPath);
        const expectedCommand = typeof expected === 'string' ? expected : expected.command;
        const actual = entry?.command ?? null;
        if (actual !== expectedCommand) {
          if (!writeMode || !entry) {
            throw new Error(
              `Hand-edited shell string detected in ${filePath} (${dottedPath}). It no longer matches src/build/hook-shell-template.ts. ` +
              `Regenerate via \`node scripts/build-hooks.js --write-shell-templates\` after an intentional generator change.`
            );
          }
          entry.command = expectedCommand;
          dirty = true;
        }
        if (typeof expected !== 'string' && Object.prototype.hasOwnProperty.call(expected, 'commandWindows')) {
          const actualWindows = entry?.commandWindows ?? null;
          if (actualWindows !== expected.commandWindows) {
            if (!writeMode || !entry) {
              throw new Error(
                `Hand-edited Windows shell string detected in ${filePath} (${dottedPath}). It no longer matches src/build/hook-shell-template.ts. ` +
                `Regenerate via \`node scripts/build-hooks.js --write-shell-templates\` after an intentional generator change.`
              );
            }
            entry.commandWindows = expected.commandWindows;
            dirty = true;
          }
        }
        if (typeof expected !== 'string' && Object.prototype.hasOwnProperty.call(expected, 'timeout')
          && entry?.timeout !== expected.timeout) {
          if (!writeMode || !entry) {
            throw new Error(
              `Hand-edited timeout detected in ${filePath} (${dottedPath}). It no longer matches scripts/build-hooks.js. ` +
              `Regenerate via \`node scripts/build-hooks.js --write-shell-templates\` after an intentional generator change.`
            );
          }
          entry.timeout = expected.timeout;
          dirty = true;
        }
      }
    }
    if (spec.execEntries) {
      for (const [dottedPath, expected] of Object.entries(spec.execEntries)) {
        if (applyCanonicalExecEntry(parsed, dottedPath, expected, filePath, writeMode)) dirty = true;
      }
      verifyClaudeCodeRuntimeHooksAreExecForm(parsed, spec.execEntries, buildEnsureLauncherExecHook(), filePath);
    }
    if (dirty) {
      fs.writeFileSync(filePath, JSON.stringify(parsed, null, 2) + '\n');
      console.log(`  ✏️  Regenerated shell templates in ${filePath}`);
    }
  }

  // Rule C safety net (bun-runner.js fixBrokenScriptPath) must stay documented.
  const bunRunner = fs.readFileSync('plugin/scripts/bun-runner.js', 'utf-8');
  if (!bunRunner.includes('function fixBrokenScriptPath')) {
    throw new Error(
      'plugin/scripts/bun-runner.js is missing fixBrokenScriptPath — it is the Rule C runtime safety net behind Rule A. Do not remove it.'
    );
  }

  // Parser-compat guard (issue #2791): bun-runner.js is invoked by hosts that
  // may run a pre-ES2020 Node whose ESM loader throws on optional chaining.
  // Strip comments, then forbid `?.` / `??` in executable code.
  const bunRunnerCode = bunRunner
    .replace(/\/\*[\s\S]*?\*\//g, '')
    .replace(/(^|[^:])\/\/.*$/gm, '$1');
  if (/\?\.|\?\?/.test(bunRunnerCode)) {
    throw new Error(
      'plugin/scripts/bun-runner.js uses optional chaining (?.) or nullish coalescing (??) — ' +
      'this launcher must parse on pre-ES2020 Node (issue #2791). Rewrite with explicit guards.'
    );
  }

  console.log('✓ Rule A shell templates match the canonical generator');
}

async function buildHooks() {
  console.log('🔨 Building claude-mem hooks and worker service...\n');

  try {
    const piBuild = preparePiExtensionBuild();
    preflightDshAttribution();
    const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf-8'));
    const version = packageJson.version;
    console.log(`📌 Version: ${version}`);

    console.log('\n📦 Preparing output directories...');
    const hooksDir = 'plugin/scripts';
    const uiDir = 'plugin/ui';

    if (!fs.existsSync(hooksDir)) {
      fs.mkdirSync(hooksDir, { recursive: true });
    }
    if (!fs.existsSync(uiDir)) {
      fs.mkdirSync(uiDir, { recursive: true });
    }
    console.log('✓ Output directories ready');

    console.log('\n📦 Generating plugin package.json...');
    const onnxruntimeNode = '1.23.2';
    const pluginPackageJson = {
      name: 'claude-mem-plugin',
      version: version,
      private: true,
      description: 'Runtime dependencies for claude-mem bundled hooks',
      type: 'module',
      dependencies: {
        // Native decoder must remain external and be installed for each host.
        // https://sharp.pixelplumbing.com/install/#bundlers
        'sharp': packageJson.dependencies.sharp,
        'zod': '^4.6.6',
        // better-auth stays external in the bundles below (~3.7MB), so the
        // worker's /api/auth/* routes (Pro sign-in) resolve it from
        // plugin/node_modules at request time — the same pattern as sharp.
        // Without these entries a plugin install has no better-auth at all
        // and every auth request 500s with "Cannot find module 'better-auth'"
        // (#5453).
        'better-auth': packageJson.dependencies['better-auth'],
        '@better-auth/api-key': packageJson.dependencies['@better-auth/api-key'],
        // Exact, not a range: the worker only installs a tree-sitter executable
        // whose SHA-256 is pinned for this version
        // (src/services/smart-file-read/tree-sitter-cli-checksums.ts), and an
        // install that ignores bun.lock (npm) would resolve a range to a newer,
        // unpinned release and leave smart_outline without an executable.
        'tree-sitter-cli': '0.26.9',
        'tree-sitter-c': '^0.24.1',
        'tree-sitter-cpp': '^0.23.4',
        'tree-sitter-go': '^0.25.0',
        'tree-sitter-java': '^0.23.5',
        'tree-sitter-javascript': '^0.25.0',
        'tree-sitter-python': '^0.25.0',
        'tree-sitter-ruby': '^0.23.1',
        'tree-sitter-rust': '^0.24.0',
        'tree-sitter-typescript': '^0.23.2',
        'tree-sitter-kotlin': '^0.3.8',
        'tree-sitter-swift': '^0.7.1',
        'tree-sitter-php': '^0.24.2',
        '@tree-sitter-grammars/tree-sitter-lua': '^0.4.1',
        'tree-sitter-scala': '^0.24.0',
        'tree-sitter-bash': '^0.25.1',
        'tree-sitter-haskell': '^0.23.1',
        '@tree-sitter-grammars/tree-sitter-zig': '^1.1.2',
        'tree-sitter-css': '^0.25.0',
        'tree-sitter-scss': '^1.0.0',
        '@tree-sitter-grammars/tree-sitter-toml': '^0.7.0',
        '@tree-sitter-grammars/tree-sitter-yaml': '^0.7.1',
        '@derekstride/tree-sitter-sql': '^0.3.11',
        '@tree-sitter-grammars/tree-sitter-markdown': '^0.3.2',
        // Exact, not a range: tree-sitter-delphi has one maintainer and one
        // published version, and its package.json points at a repository that
        // does not exist (the sources match github.com/sammedhi/tree-sitter-delphi).
        // Its C sources are compiled and loaded whenever a Pascal file is parsed,
        // so a new version must arrive as a reviewed bump, never through a range.
        'tree-sitter-delphi': '0.1.0',
        'shell-quote': '1.11.0',
      },
      // Keep the ~300 MB server embedder in its own dependency workspace.
      // Plugin installs filter to this root instead of globally omitting
      // optional dependencies, which sharp needs for its native decoder.
      // Server starts and Docker installs include the workspace; bunfig.toml
      // retains the hoisted module paths used by the external bundle imports.
      workspaces: ['server-runtime'],
      overrides: {
        'tree-sitter': '^0.25.0',
        // MUST live here, not only in the root package.json. npm/bun apply
        // `overrides` ONLY in the project being installed, so the root override is
        // invisible to users; plugin/ is its own install root (own package.json +
        // own bun.lock, installed by setup-runtime.ts), so this one DOES apply.
        // Without it, @huggingface/transformers' EXACT transitive pin wins
        // ("onnxruntime-node": "1.30.0" in transformers 4.3.1), and ONNX Runtime
        // ships no macOS x86_64 binary from 1.24 on (v1.24.1 release notes), so
        // every Intel Mac would lose search by meaning, as in #3199. 1.23.2 is
        // the last release with all six targets, {linux,darwin,win32} x
        // {x64,arm64}, and the version uv resolves Chroma's `onnxruntime>=1.20`
        // to on an Intel Mac. Its vectors are bit-identical to 1.21.0's.
        'onnxruntime-node': onnxruntimeNode,
        // A workaround, not a real package: transformers lists onnxruntime-web
        // (a 141 MB nightly) as a hard dependency, but its Node build runs on
        // onnxruntime-node and never loads it. This points the name at
        // onnxruntime-common, which onnxruntime-node already installs, so it
        // downloads nothing. Remove it once transformers.js stops requiring
        // onnxruntime-web under Node.
        'onnxruntime-web': `npm:onnxruntime-common@${onnxruntimeNode}`,
        // onnxruntime-node 1.23.2 asks for adm-zip ^0.5.16, which stays on the
        // 0.5 line and its High advisories (#6211); 0.6.1 fixes them all.
        'adm-zip': '^0.6.1'
      },
      trustedDependencies: [
        'tree-sitter-cli'
      ],
      // npm 11.16+ runs dependency install scripts only for packages listed in
      // `allowScripts` — npm's counterpart to bun's `trustedDependencies` above.
      // Sourced from scripts/postinstall-allowlist.js so it can never drift from
      // the CI guard.
      allowScripts: allowScriptsMap(),
      engines: {
        node: '>=20.12.0',
        bun: packageJson.engines.bun
      }
    };
    fs.writeFileSync('plugin/package.json', JSON.stringify(pluginPackageJson, null, 2) + '\n');
    console.log('✓ plugin/package.json generated');
    const serverRuntimePath = 'plugin/server-runtime/package.json';
    const serverRuntimeManifest = JSON.parse(fs.readFileSync(serverRuntimePath, 'utf8'));
    serverRuntimeManifest.version = version;
    fs.writeFileSync(serverRuntimePath, JSON.stringify(serverRuntimeManifest, null, 2) + '\n');

    console.log('\n📋 Building React viewer...');
    const { spawn } = await import('child_process');
    const viewerBuild = spawn('node', ['scripts/build-viewer.js'], { stdio: 'inherit' });
    await new Promise((resolve, reject) => {
      viewerBuild.on('exit', (code) => {
        if (code === 0) {
          resolve();
        } else {
          reject(new Error(`Viewer build failed with exit code ${code}`));
        }
      });
    });

    console.log(`\n🔧 Building worker service...`);
    await build({
      entryPoints: [WORKER_SERVICE.source],
      plugins: [deepSearchBuildPlugin()],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'cjs',
      outfile: `${hooksDir}/${WORKER_SERVICE.name}.cjs`,
      // Zod is inlined, and the worker's dynamic imports make esbuild wrap it in
      // lazy initializers. `zod/v4` (imported by @modelcontextprotocol/sdk) is a
      // pure `export *` re-export of that wrapped code, and esbuild emits no
      // initializer call through it, so the SDK's top-level `z.custom()` ran
      // before Zod's classes existed and the worker crashed on load. One Zod
      // entry point gets initialized correctly. The self-contained bundle test
      // (tests/infrastructure/worker-bundle-self-contained.test.ts) guards this.
      alias: { 'zod/v4': 'zod' },
      minify: true,
      ...SOURCEMAP_OPTS,
      logLevel: 'error', // Suppress warnings (import.meta warning is benign)
      external: [
        'sharp',
        'bun:sqlite',
        // bun:ffi backs Windows listen-socket HANDLE_FLAG_INHERIT clearing (#3300).
        'bun:ffi',
        'cohere-ai',
        'ollama',
        '@chroma-core/default-embed',
        'onnxruntime-node',
        // better-auth (~3.7MB) is only reachable through BetterAuthRoutes' request-time
        // dynamic import('better-auth/node') / import('./auth.js'). esbuild otherwise
        // inlines that dynamic-import target into the worker bundle, dragging in the full
        // better-auth library (kysely, oauth, nanoid, …). Keeping it external strips
        // the dead weight from worker-service.cjs. The routes DO exercise it (Pro
        // sign-in), so plugin/package.json ships better-auth + @better-auth/api-key
        // (see the generated manifest above) and the imports resolve from
        // plugin/node_modules. See #2584, #5453.
        'better-auth',
        'better-auth/node',
        'better-auth/plugins',
        'better-auth/db/migration',
        '@better-auth/api-key',
        ...POSTHOG_OPTIONAL_IMPORTS,
      ],
      define: {
        '__DEFAULT_PACKAGE_VERSION__': `"${version}"`,
        ...DIRNAME_DEFINE,
        // Polyfill import.meta.url for ESM deps bundled into CJS output.
        // @anthropic-ai/claude-agent-sdk's *.mjs files use createRequire(import.meta.url)
        // and `new URL(rel, import.meta.url)`. We map import.meta.url to a file:// URL
        // (not the raw __filename path) so URL construction preserves its semantics.
        'import.meta.url': '__IMPORT_META_URL__'
      },
      banner: {
        js: [
          '#!/usr/bin/env bun',
          ...DIRNAME_BANNER,
          'var __IMPORT_META_URL__ = require("node:url").pathToFileURL(__CM_FILENAME__).href;'
        ].join('\n')
      }
    });

    assertBundleIntegrity(`${hooksDir}/${WORKER_SERVICE.name}.cjs`);

    const workerZodRequire = fs.readFileSync(`${hooksDir}/${WORKER_SERVICE.name}.cjs`, 'utf-8')
      .match(/require\(\s*["']zod(?:\/[^"']*)?["']\s*\)/);
    if (workerZodRequire) {
      throw new Error(
        `worker-service.cjs contains external ${workerZodRequire[0]}. Codex plugin caches may have no node_modules, so Zod must be bundled into the worker.`
      );
    }

    fs.chmodSync(`${hooksDir}/${WORKER_SERVICE.name}.cjs`, 0o755);
    const workerStats = fs.statSync(`${hooksDir}/${WORKER_SERVICE.name}.cjs`);
    console.log(`✓ worker-service built (${(workerStats.size / 1024).toFixed(2)} KB)`);

    console.log(`\n🔧 Building hook service...`);
    await build({
      entryPoints: [HOOK_SERVICE.source],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'cjs',
      outfile: `${hooksDir}/${HOOK_SERVICE.name}.cjs`,
      alias: { 'zod/v4': 'zod' },
      minify: true,
      ...SOURCEMAP_OPTS,
      logLevel: 'error',
      external: [
        'sharp', 'bun:sqlite', 'bun:ffi', 'cohere-ai', 'ollama', '@chroma-core/default-embed', 'onnxruntime-node',
        'better-auth', 'better-auth/node', 'better-auth/plugins', 'better-auth/db/migration', '@better-auth/api-key',
        ...POSTHOG_OPTIONAL_IMPORTS,
      ],
      define: {
        '__DEFAULT_PACKAGE_VERSION__': JSON.stringify(version),
        ...DIRNAME_DEFINE,
        'import.meta.url': '__IMPORT_META_URL__'
      },
      banner: {
        js: [
          '#!/usr/bin/env bun',
          ...DIRNAME_BANNER,
          'var __IMPORT_META_URL__ = require("node:url").pathToFileURL(__CM_FILENAME__).href;'
        ].join('\n')
      }
    });
    assertBundleIntegrity(`${hooksDir}/${HOOK_SERVICE.name}.cjs`);
    fs.chmodSync(`${hooksDir}/${HOOK_SERVICE.name}.cjs`, 0o755);
    const hookServiceStats = fs.statSync(`${hooksDir}/${HOOK_SERVICE.name}.cjs`);
    console.log(`✓ hook-service built (${(hookServiceStats.size / 1024).toFixed(2)} KB)`);
    // Hard budget, unlike the worker's advisory one: the point of this bundle is
    // to stay cheap to parse. A jump means a worker-sized dependency was pulled
    // into the hook path; fix the import instead of raising the number.
    // Basis: measured 782 KB at 96bb200f7 (2026-11-09, #5541); 1200 KB is ~50%
    // headroom and still a quarter of worker-service.cjs (4.7 MB), whose parse
    // cost this bundle exists to avoid.
    const HOOK_SERVICE_MAX_BYTES = 1200 * 1024;
    if (hookServiceStats.size > HOOK_SERVICE_MAX_BYTES) {
      throw new Error(
        `hook-service.cjs is ${(hookServiceStats.size / 1024).toFixed(2)} KB (budget ${(HOOK_SERVICE_MAX_BYTES / 1024).toFixed(0)} KB). ` +
        `A heavy module leaked into the hook path (src/cli/hook-entry.ts import graph).`
      );
    }

    await build({
      entryPoints: [CONTEXT_READ_WORKER.source],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'cjs',
      outfile: `${hooksDir}/${CONTEXT_READ_WORKER.name}.cjs`,
      alias: { 'zod/v4': 'zod' },
      minify: true,
      ...SOURCEMAP_OPTS,
      logLevel: 'error',
      external: [
        'bun:sqlite', 'bun:ffi', 'cohere-ai', 'ollama', '@chroma-core/default-embed', 'onnxruntime-node',
        'better-auth', 'better-auth/node', 'better-auth/plugins', 'better-auth/db/migration', '@better-auth/api-key',
        ...POSTHOG_OPTIONAL_IMPORTS,
      ],
      define: {
        '__DEFAULT_PACKAGE_VERSION__': JSON.stringify(version),
        ...DIRNAME_DEFINE,
        // Bun 1.3.13 inlines process.env.KEY when transpiling Worker entries,
        // then reuses those values from its content-keyed disk cache in another
        // process. Keep the environment object dynamic so a relocated bundle
        // never opens a previous run's database/config directory.
        'process.env': '__CM_RUNTIME_ENV__',
        'import.meta.url': '__IMPORT_META_URL__'
      },
      banner: {
        js: [
          ...DIRNAME_BANNER,
          'var __CM_RUNTIME_ENV__ = process.env;',
          'var __IMPORT_META_URL__ = require("node:url").pathToFileURL(__CM_FILENAME__).href;'
        ].join('\n')
      }
    });
    assertBundleIntegrity(`${hooksDir}/${CONTEXT_READ_WORKER.name}.cjs`);

    await build({
      entryPoints: [WORK_VIEW_READ_WORKER.source],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'cjs',
      outfile: `${hooksDir}/${WORK_VIEW_READ_WORKER.name}.cjs`,
      minify: true,
      ...SOURCEMAP_OPTS,
      logLevel: 'error',
      external: ['bun:sqlite'],
      define: {
        ...DIRNAME_DEFINE,
        'import.meta.url': '__IMPORT_META_URL__'
      },
      banner: {
        js: [
          ...DIRNAME_BANNER,
          'var __IMPORT_META_URL__ = require("node:url").pathToFileURL(__CM_FILENAME__).href;'
        ].join('\n')
      }
    });
    assertBundleIntegrity(`${hooksDir}/${WORK_VIEW_READ_WORKER.name}.cjs`);

    // Advisory only — a sudden jump usually means a heavy server-only dependency
    // (better-auth, kysely, a database driver) leaked into the worker bundle via a
    // transitive import (#2584). Never blocks the build.
    const WORKER_SERVICE_MAX_BYTES = 2900 * 1024;
    if (workerStats.size > WORKER_SERVICE_MAX_BYTES) {
      console.warn(
        `⚠️  worker-service.cjs is ${(workerStats.size / 1024).toFixed(2)} KB (advisory budget ${(WORKER_SERVICE_MAX_BYTES / 1024).toFixed(0)} KB). ` +
        `If this jumped unexpectedly, check whether a server-only dependency leaked into the worker bundle (see #2584).`
      );
    }

    // worker-service.cjs lazy-requires these via createRequire("../sqlite/…"),
    // intentionally kept external from the worker bundle (#2584). They must ship
    // as sibling files under plugin/sqlite/, or clean installs can throw
    // "Cannot find module '../sqlite/SessionStore.js'" when Chroma vector sync
    // reaches the SQLite helpers (#3107/#3126).
    console.log(`\n🔧 Building sqlite runtime modules...`);
    const SQLITE_MODULES = [
      { source: 'src/services/sqlite/SessionStore.ts', out: 'plugin/sqlite/SessionStore.js' },
      { source: 'src/services/sqlite/observations/files.ts', out: 'plugin/sqlite/observations/files.js' },
    ];
    for (const mod of SQLITE_MODULES) {
      fs.mkdirSync(path.dirname(mod.out), { recursive: true });
      await build({
        entryPoints: [mod.source],
        bundle: true,
        platform: 'node',
        target: 'node18',
        format: 'cjs',
        outfile: mod.out,
        minify: true,
        ...SOURCEMAP_OPTS,
        logLevel: 'error',
        external: [
          'bun:sqlite',
          'zod',
          'cohere-ai',
          'ollama',
          '@chroma-core/default-embed',
          'onnxruntime-node',
          'better-auth',
          'better-auth/node',
          'better-auth/plugins',
          'better-auth/db/migration',
          '@better-auth/api-key',
        ],
        define: {
          '__DEFAULT_PACKAGE_VERSION__': `"${version}"`,
          ...DIRNAME_DEFINE,
          'import.meta.url': '__IMPORT_META_URL__'
        },
        banner: {
          js: [
            ...DIRNAME_BANNER,
            'var __IMPORT_META_URL__ = require("node:url").pathToFileURL(__CM_FILENAME__).href;'
          ].join('\n')
        }
      });
      assertBundleIntegrity(mod.out);
      console.log(`✓ ${mod.out} built (${(fs.statSync(mod.out).size / 1024).toFixed(2)} KB)`);
    }

    // The request-progress skill runs this with bun to group conversations
    // into overall requests and record progress reviews for My Work.
    const REQUEST_GROUPS_CLI = 'plugin/skills/request-progress/scripts/request-groups.mjs';
    await build({
      entryPoints: ['src/services/work-view/request-groups-cli.mjs'],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'esm',
      outfile: REQUEST_GROUPS_CLI,
      logLevel: 'error',
      external: ['bun:sqlite'],
    });
    console.log(`✓ ${REQUEST_GROUPS_CLI} built (${(fs.statSync(REQUEST_GROUPS_CLI).size / 1024).toFixed(2)} KB)`);

    console.log(`\n🔧 Building server beta service...`);
    await build({
      entryPoints: [SERVER_SERVICE.source],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'cjs',
      outfile: `${hooksDir}/${SERVER_SERVICE.name}.cjs`,
      minify: true,
      ...SOURCEMAP_OPTS,
      logLevel: 'error',
      external: [
        'bun:sqlite',
        // bun:ffi backs Windows listen-socket HANDLE_FLAG_INHERIT clearing (#3300).
        'bun:ffi',
        'zod',
        // @huggingface/transformers is reached ONLY through LocalEmbedder's
        // request-time `await import('@huggingface/transformers')`. Bundling it
        // inlines the ONNX runtime glue while onnxruntime-node / sharp stay
        // external, so the lazy path dies on a real install with
        // "Cannot find module 'onnxruntime-node'". Keeping the whole trio external
        // makes the dynamic import resolve against plugin/node_modules, where
        // plugin/package.json ships them (and pins onnxruntime-node; see its
        // overrides above).
        'onnxruntime-node',
        '@huggingface/transformers',
        'sharp',
      ],
      define: {
        '__DEFAULT_PACKAGE_VERSION__': `"${version}"`,
        ...DIRNAME_DEFINE
      },
      banner: {
        js: [
          '#!/usr/bin/env bun',
          ...DIRNAME_BANNER
        ].join('\n')
      }
    });

    assertBundleIntegrity(`${hooksDir}/${SERVER_SERVICE.name}.cjs`);

    fs.chmodSync(`${hooksDir}/${SERVER_SERVICE.name}.cjs`, 0o755);
    const serverStats = fs.statSync(`${hooksDir}/${SERVER_SERVICE.name}.cjs`);
    console.log(`✓ server-service built (${(serverStats.size / 1024).toFixed(2)} KB)`);

    console.log(`\n🔧 Building MCP server...`);
    await build({
      entryPoints: [MCP_SERVER.source],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'cjs',
      outfile: `${hooksDir}/${MCP_SERVER.name}.cjs`,
      minify: true,
      ...SOURCEMAP_OPTS,
      logLevel: 'error',
      external: [
        'bun:sqlite',
        'tree-sitter-cli',
        'tree-sitter-javascript',
        'tree-sitter-typescript',
        'tree-sitter-python',
        'tree-sitter-go',
        'tree-sitter-rust',
        'tree-sitter-ruby',
        'tree-sitter-java',
        'tree-sitter-c',
        'tree-sitter-cpp',
        'tree-sitter-kotlin',
        'tree-sitter-swift',
        'tree-sitter-php',
        '@tree-sitter-grammars/tree-sitter-lua',
        'tree-sitter-scala',
        'tree-sitter-bash',
        'tree-sitter-haskell',
        '@tree-sitter-grammars/tree-sitter-zig',
        'tree-sitter-css',
        'tree-sitter-scss',
        '@tree-sitter-grammars/tree-sitter-toml',
        '@tree-sitter-grammars/tree-sitter-yaml',
        '@derekstride/tree-sitter-sql',
        '@tree-sitter-grammars/tree-sitter-markdown',
        'tree-sitter-delphi',
      ],
      define: {
        '__DEFAULT_PACKAGE_VERSION__': `"${version}"`,
        ...DIRNAME_DEFINE
      },
      banner: {
        js: [
          '#!/usr/bin/env node',
          ...DIRNAME_BANNER
        ].join('\n')
      }
    });

    assertBundleIntegrity(`${hooksDir}/${MCP_SERVER.name}.cjs`);

    fs.chmodSync(`${hooksDir}/${MCP_SERVER.name}.cjs`, 0o755);
    const mcpServerStats = fs.statSync(`${hooksDir}/${MCP_SERVER.name}.cjs`);
    console.log(`✓ mcp-server built (${(mcpServerStats.size / 1024).toFixed(2)} KB)`);

    const mcpBundleContent = fs.readFileSync(`${hooksDir}/${MCP_SERVER.name}.cjs`, 'utf-8');
    const bunRequireRegex = /require\(\s*["']bun:[a-z][a-z0-9_-]*["']\s*\)/;
    const bunRequireMatch = mcpBundleContent.match(bunRequireRegex);
    if (bunRequireMatch) {
      throw new Error(
        `mcp-server.cjs contains a Bun-only ${bunRequireMatch[0]} call. This means a transitive import in src/servers/mcp-server.ts pulled in code from worker-service.ts (or another module that touches DatabaseManager/ChromaSync). The MCP server runs under Node and cannot load bun:* modules. Audit recent imports in src/servers/mcp-server.ts and src/services/worker-spawner.ts — the spawner module is intentionally lightweight and MUST NOT import anything that touches SQLite or other Bun-only modules. See PR #1645 for context.`
      );
    }
    const zodRequireRegex = /require\(\s*["']zod(?:\/[^"']*)?["']\s*\)/;
    const zodRequireMatch = mcpBundleContent.match(zodRequireRegex);
    if (zodRequireMatch) {
      throw new Error(
        `mcp-server.cjs contains external ${zodRequireMatch[0]}. Claude Desktop can launch this bundle without plugin node_modules available, so Zod must be bundled into the MCP server.`
      );
    }

    const MCP_SERVER_MAX_BYTES = 600 * 1024;
    if (mcpServerStats.size > MCP_SERVER_MAX_BYTES) {
      console.warn(
        `⚠️  mcp-server.cjs is ${(mcpServerStats.size / 1024).toFixed(2)} KB (advisory budget ${(MCP_SERVER_MAX_BYTES / 1024).toFixed(0)} KB). If this jumped unexpectedly, a transitive import may have pulled worker-service.ts or another heavy module into the MCP bundle (see #1645).`
      );
    }

    console.log(`\n🔧 Building context generator...`);
    await build({
      entryPoints: [CONTEXT_GENERATOR.source],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'cjs',
      outfile: `${hooksDir}/${CONTEXT_GENERATOR.name}.cjs`,
      minify: true,
      ...SOURCEMAP_OPTS,
      logLevel: 'error',
      external: ['bun:sqlite', 'zod'],
      define: {
        '__DEFAULT_PACKAGE_VERSION__': `"${version}"`,
        ...DIRNAME_DEFINE
      },
      banner: {
        js: DIRNAME_BANNER.join('\n')
      }
    });

    assertBundleIntegrity(`${hooksDir}/${CONTEXT_GENERATOR.name}.cjs`);

    const contextGenStats = fs.statSync(`${hooksDir}/${CONTEXT_GENERATOR.name}.cjs`);
    console.log(`✓ context-generator built (${(contextGenStats.size / 1024).toFixed(2)} KB)`);

    console.log(`\n🔧 Building transcript watcher...`);
    await build({
      entryPoints: [TRANSCRIPT_WATCHER.source],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'cjs',
      outfile: `${hooksDir}/${TRANSCRIPT_WATCHER.name}.cjs`,
      minify: true,
      ...SOURCEMAP_OPTS,
      logLevel: 'error',
      // Externalize zod for consistency with server-service, context-generator and the other plugin bundles —
      // any zod usage in the processor.ts import chain resolves at runtime against
      // plugin/node_modules instead of being inlined (keeps the bundle slim). The
      // worker and MCP server inline zod because a Codex or Claude Desktop copy of
      // the plugin may have no node_modules.
      // processor.ts reaches ingestObservation's lazy media converter; keep
      // the native decoder external exactly as the worker bundle does.
      external: ['sharp', 'bun:sqlite', 'zod', ...POSTHOG_OPTIONAL_IMPORTS],
      define: {
        '__DEFAULT_PACKAGE_VERSION__': `"${version}"`,
        ...DIRNAME_DEFINE
      },
      banner: {
        js: [
          '#!/usr/bin/env bun',
          ...DIRNAME_BANNER
        ].join('\n')
      }
    });

    assertBundleIntegrity(`${hooksDir}/${TRANSCRIPT_WATCHER.name}.cjs`);

    fs.chmodSync(`${hooksDir}/${TRANSCRIPT_WATCHER.name}.cjs`, 0o755);
    const transcriptWatcherStats = fs.statSync(`${hooksDir}/${TRANSCRIPT_WATCHER.name}.cjs`);
    console.log(`✓ transcript-watcher built (${(transcriptWatcherStats.size / 1024).toFixed(2)} KB)`);

    // Advisory only — the watcher is meant to be a thin file-tail loop.
    const TRANSCRIPT_WATCHER_MAX_BYTES = 200 * 1024;
    if (transcriptWatcherStats.size > TRANSCRIPT_WATCHER_MAX_BYTES) {
      console.warn(
        `⚠️  transcript-watcher.cjs is ${(transcriptWatcherStats.size / 1024).toFixed(2)} KB (advisory budget ${(TRANSCRIPT_WATCHER_MAX_BYTES / 1024).toFixed(0)} KB). If this jumped unexpectedly, check src/services/transcripts/processor.ts and watcher.ts for heavy imports.`
      );
    }

    console.log(`\n🔧 Building claude-mem hook launcher...`);
    await build({
      entryPoints: [HOOK_LAUNCHER.source],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'cjs',
      outfile: `${hooksDir}/${HOOK_LAUNCHER.name}.cjs`,
      minify: true,
      ...SOURCEMAP_OPTS,
      logLevel: 'error',
      banner: {
        js: '#!/usr/bin/env bun'
      }
    });

    assertBundleIntegrity(`${hooksDir}/${HOOK_LAUNCHER.name}.cjs`);

    fs.chmodSync(`${hooksDir}/${HOOK_LAUNCHER.name}.cjs`, 0o755);
    const hookLauncherStats = fs.statSync(`${hooksDir}/${HOOK_LAUNCHER.name}.cjs`);
    console.log(`✓ claude-mem-launcher built (${(hookLauncherStats.size / 1024).toFixed(2)} KB)`);

    console.log(`\n🔧 Building ensure-launcher self-heal...`);
    await build({
      entryPoints: [ENSURE_LAUNCHER.source],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'cjs',
      outfile: `${hooksDir}/${ENSURE_LAUNCHER.name}.cjs`,
      minify: true,
      ...SOURCEMAP_OPTS,
      logLevel: 'error',
      banner: {
        js: '#!/usr/bin/env node'
      }
    });

    assertBundleIntegrity(`${hooksDir}/${ENSURE_LAUNCHER.name}.cjs`);

    fs.chmodSync(`${hooksDir}/${ENSURE_LAUNCHER.name}.cjs`, 0o755);
    const ensureLauncherStats = fs.statSync(`${hooksDir}/${ENSURE_LAUNCHER.name}.cjs`);
    console.log(`✓ ensure-launcher built (${(ensureLauncherStats.size / 1024).toFixed(2)} KB)`);

    console.log(`\n🔧 Building the Claude Code hooks module...`);
    await build({
      entryPoints: [HOOKS_MODULE.source],
      bundle: true,
      // A Claude Code hooks module is an ES module with no Node APIs, read as
      // source (Claude Code lists its hooks and $ calls off the text), so it is
      // neither minified nor given Node shims.
      platform: 'neutral',
      target: 'es2022',
      format: 'esm',
      outfile: HOOKS_MODULE.outfile,
      minify: false,
      legalComments: 'none',
      logLevel: 'error',
      banner: {
        js: '// Built from src/mods/ by scripts/build-hooks.js. Edit the source, not this file.'
      }
    });
    assertModBundle(HOOKS_MODULE.outfile);
    const claudeCodeHooksJson = JSON.parse(fs.readFileSync('plugin/hooks/hooks.json', 'utf-8'));
    if (!isDeepStrictEqual(claudeCodeHooksJson.modules, HOOKS_MODULE.hooksJsonModules)) {
      throw new Error(
        `plugin/hooks/hooks.json \`modules\` must be ${JSON.stringify(HOOKS_MODULE.hooksJsonModules)} (found ${JSON.stringify(claudeCodeHooksJson.modules)}). ` +
        'Claude Code loads one hooks module per plugin and refuses a second entry.'
      );
    }
    const hooksModuleStats = fs.statSync(HOOKS_MODULE.outfile);
    console.log(`✓ hooks module built (${(hooksModuleStats.size / 1024).toFixed(2)} KB)`);

    console.log(`\n🔧 Building NPX CLI...`);
    const npxCliOutDir = 'dist/npx-cli';
    if (!fs.existsSync(npxCliOutDir)) {
      fs.mkdirSync(npxCliOutDir, { recursive: true });
    }
    await build({
      entryPoints: ['src/npx-cli/index.ts'],
      bundle: true,
      platform: 'node',
      target: 'node18',
      format: 'esm',
      outfile: `${npxCliOutDir}/index.js`,
      banner: { js: '#!/usr/bin/env node' },
      minify: true,
      logLevel: 'error',
      external: [
        'fs', 'fs/promises', 'path', 'os', 'child_process', 'url',
        'crypto', 'http', 'https', 'net', 'stream', 'util', 'events',
        'buffer', 'querystring', 'readline', 'tty', 'assert',
        'bun:sqlite',
      ],
      define: {
        '__DEFAULT_PACKAGE_VERSION__': `"${version}"`
      },
    });

    fs.chmodSync(`${npxCliOutDir}/index.js`, 0o755);
    const npxCliStats = fs.statSync(`${npxCliOutDir}/index.js`);
    console.log(`✓ npx-cli built (${(npxCliStats.size / 1024).toFixed(2)} KB)`);

    console.log(`\n🔧 Building bug-report CLI...`);
    const bugReportOutDir = 'dist/bug-report';
    if (!fs.existsSync(bugReportOutDir)) {
      fs.mkdirSync(bugReportOutDir, { recursive: true });
    }
    await build({
      entryPoints: ['scripts/bug-report/cli.ts'],
      bundle: true,
      platform: 'node',
      target: 'node20',
      format: 'esm',
      outfile: `${bugReportOutDir}/index.js`,
      minify: true,
      logLevel: 'error',
      external: [
        'fs', 'fs/promises', 'path', 'os', 'child_process', 'url',
        'crypto', 'http', 'https', 'net', 'stream', 'util', 'events',
        'buffer', 'querystring', 'readline', 'tty', 'assert',
        'bun:sqlite',
      ],
    });

    fs.chmodSync(`${bugReportOutDir}/index.js`, 0o755);
    const bugReportStats = fs.statSync(`${bugReportOutDir}/index.js`);
    console.log(`✓ bug-report built (${(bugReportStats.size / 1024).toFixed(2)} KB)`);

    if (fs.existsSync('openclaw/src/index.ts')) {
      console.log(`\n🔧 Building OpenClaw plugin...`);
      const openclawOutDir = 'openclaw/dist';
      if (!fs.existsSync(openclawOutDir)) {
        fs.mkdirSync(openclawOutDir, { recursive: true });
      }
      await build({
        entryPoints: ['openclaw/src/index.ts'],
        bundle: true,
        platform: 'node',
        target: 'node18',
        format: 'esm',
        outfile: `${openclawOutDir}/index.js`,
        minify: true,
        logLevel: 'error',
        external: [
          'fs', 'fs/promises', 'path', 'os', 'child_process', 'url',
          'crypto', 'http', 'https', 'net', 'stream', 'util', 'events',
        ],
      });

      const openclawStats = fs.statSync(`${openclawOutDir}/index.js`);
      console.log(`✓ openclaw plugin built (${(openclawStats.size / 1024).toFixed(2)} KB)`);
    }

    // claude-mem/eve: memory provider for eve agents. eve and zod come from the
    // consuming agent (optional peer dependencies), so they stay external.
    console.log(`\n🔧 Building eve memory provider...`);
    const eveOutDir = 'dist/eve';
    fs.mkdirSync(eveOutDir, { recursive: true });
    await build({
      entryPoints: ['integrations/eve/provider/src/index.ts'],
      bundle: true,
      platform: 'node',
      target: 'node24',
      format: 'esm',
      outfile: `${eveOutDir}/index.js`,
      logLevel: 'error',
      external: ['eve', 'eve/*', 'zod', 'node:*'],
    });
    fs.copyFileSync('integrations/eve/provider/types/index.d.ts', `${eveOutDir}/index.d.ts`);
    console.log(`✓ eve memory provider built (${(fs.statSync(`${eveOutDir}/index.js`).size / 1024).toFixed(2)} KB)`);

    if (fs.existsSync('src/integrations/opencode-plugin/index.ts')) {
      console.log(`\n🔧 Building OpenCode plugin...`);
      const opencodeOutDir = 'dist/opencode-plugin';
      if (!fs.existsSync(opencodeOutDir)) {
        fs.mkdirSync(opencodeOutDir, { recursive: true });
      }
      await build({
        ...OPENCODE_PLUGIN_BUILD_OPTIONS,
        outfile: `${opencodeOutDir}/index.js`,
      });

      const opencodeStats = fs.statSync(`${opencodeOutDir}/index.js`);
      console.log(`✓ opencode plugin built (${(opencodeStats.size / 1024).toFixed(2)} KB)`);
    }

    fs.mkdirSync('dist/pi-extension', { recursive: true });
    await build({ ...piBuild.options, outfile: 'dist/pi-extension/index.js' });
    for (const file of piBuild.attributionFiles) fs.writeFileSync(path.join('dist/pi-extension', file.name), file.contents);
    console.log('✓ Pi memory extension built');
    fs.mkdirSync('dsh/lib', { recursive: true });
    const dshManifest = JSON.parse(fs.readFileSync('dsh/package.json', 'utf8'));
    dshManifest.version = JSON.parse(fs.readFileSync('package.json', 'utf8')).version;
    fs.writeFileSync('dsh/package.json', JSON.stringify(dshManifest, null, 2) + '\n');
    await build({ ...DSH_PLUGIN_BUILD_OPTIONS, outfile: 'dsh/lib/index.js' });
    console.log('✓ DeepSeek Harness memory plugin built');

    console.log('\n📋 Copying onboarding explainer to plugin tree...');
    const onboardingExplainerSrc = 'src/services/worker/onboarding-explainer.md';
    const onboardingExplainerDst = 'plugin/skills/how-it-works/onboarding-explainer.md';
    if (!fs.existsSync(onboardingExplainerSrc)) {
      throw new Error(`Missing onboarding explainer source: ${onboardingExplainerSrc}`);
    }
    fs.mkdirSync(path.dirname(onboardingExplainerDst), { recursive: true });
    fs.copyFileSync(onboardingExplainerSrc, onboardingExplainerDst);
    console.log(`✓ Copied ${onboardingExplainerSrc} → ${onboardingExplainerDst}`);

    console.log('\n📋 Verifying distribution files...');
    const validCodexHookEvents = new Set([
      'SessionStart',
      'UserPromptSubmit',
      'PreToolUse',
      'PermissionRequest',
      'PostToolUse',
      'Stop',
      'PostCompact',
      'SubagentStart',
    ]);
    const requiredDistributionFiles = [
      'plugin/skills/mem-search/SKILL.md',
      'plugin/skills/mode-creator/SKILL.md',
      'plugin/skills/mode-creator/scripts/install-mode.mjs',
      'plugin/skills/mode-creator/scripts/configure-telegram.mjs',
      'plugin/skills/smart-explore/SKILL.md',
      'plugin/skills/how-it-works/SKILL.md',
      'plugin/skills/how-it-works/onboarding-explainer.md',
      'plugin/hooks/hooks.json',
      HOOKS_MODULE.outfile,
      'plugin/hooks/codex-hooks.json',
      // Referenced by plugin/.codex-plugin/plugin.json; a missing file would
      // otherwise only surface when Codex loads the plugin.
      'plugin/hooks/codex-no-bundled-hooks.json',
      'plugin/hooks/qoder-hooks.json',
      'plugin/hooks/qoder-repo-hooks.json',
      'plugin/scripts/bun-runner.js',
      'plugin/scripts/hook-service.cjs',
      'plugin/scripts/context-read-worker.cjs',
      'plugin/scripts/context-read-worker.cjs.map',
      'plugin/scripts/work-view-read-worker.cjs',
      'plugin/scripts/work-view-read-worker.cjs.map',
      'plugin/sqlite/SessionStore.js',
      'plugin/sqlite/observations/files.js',
      'plugin/.claude-plugin/plugin.json',
      'plugin/.codex-plugin/plugin.json',
      'plugin/.qoder-plugin/plugin.json',
      'plugin/.devin-plugin/plugin.json',
      'plugin/hooks.json',
      'plugin/devin.mcp.json',
      'plugin/qoder.mcp.json',
      'plugin/scripts/qoder-hook-launcher.cjs',
      'plugin/.mcp.json',
      '.codex-plugin/plugin.json',
      '.qoder-plugin/plugin.json',
      '.agents/plugins/marketplace.json',
      'dist/bug-report/index.js',
    ];
    for (const filePath of requiredDistributionFiles) {
      if (!fs.existsSync(filePath)) {
        throw new Error(`Missing required distribution file: ${filePath}`);
      }
    }
    const codexHooks = JSON.parse(fs.readFileSync('plugin/hooks/codex-hooks.json', 'utf-8'));
    const validCodexHookRootKeys = new Set(['hooks']);
    for (const rootKey of Object.keys(codexHooks)) {
      if (!validCodexHookRootKeys.has(rootKey)) {
        throw new Error(`plugin/hooks/codex-hooks.json contains unsupported Codex root key: ${rootKey}`);
      }
    }
    for (const eventName of Object.keys(codexHooks.hooks ?? {})) {
      if (!validCodexHookEvents.has(eventName)) {
        throw new Error(`plugin/hooks/codex-hooks.json contains unknown Codex hook event: ${eventName}`);
      }
    }
    const codexMarketplace = JSON.parse(fs.readFileSync('.agents/plugins/marketplace.json', 'utf-8'));
    const claudeMemMarketplaceEntry = (codexMarketplace.plugins ?? []).find((plugin) => plugin.name === 'claude-mem');
    if (claudeMemMarketplaceEntry?.source?.path !== './plugin') {
      throw new Error('.agents/plugins/marketplace.json must point claude-mem source.path at ./plugin so Codex loads the bundled plugin root');
    }
    const bundledMcp = JSON.parse(fs.readFileSync('plugin/.mcp.json', 'utf-8'));
    const mcpSearchCommand = bundledMcp.mcpServers?.['mcp-search']?.args?.join(' ') ?? '';
    if (!mcpSearchCommand.includes('.codex/plugins/cache/claude-mem-local/claude-mem')) {
      throw new Error('plugin/.mcp.json mcp-search launcher must include Codex cache fallback for hosts that do not inject PLUGIN_ROOT');
    }
    if (!mcpSearchCommand.includes('plugins/cache/thedotmack/claude-mem')) {
      throw new Error('plugin/.mcp.json mcp-search launcher must include Claude cache fallback for hosts that do not inject PLUGIN_ROOT');
    }
    console.log('✓ All required distribution files present');

    await verifyShellTemplateCanonical();

    console.log('\n✅ All build targets compiled successfully!');
    console.log(`   Output: ${hooksDir}/`);
    console.log(`   - Worker: worker-service.cjs`);
    console.log(`   - Server: server-service.cjs`);
    console.log(`   - MCP Server: mcp-server.cjs`);
    console.log(`   - Context Generator: context-generator.cjs`);
    console.log(`   - Transcript Watcher: transcript-watcher.cjs`);
    console.log(`   Output: ${npxCliOutDir}/`);
    console.log(`   - NPX CLI: index.js`);
    if (fs.existsSync('openclaw/dist/index.js')) {
      console.log(`   Output: openclaw/dist/`);
      console.log(`   - OpenClaw Plugin: index.js`);
    }
    if (fs.existsSync('dist/opencode-plugin/index.js')) {
      console.log(`   Output: dist/opencode-plugin/`);
      console.log(`   - OpenCode Plugin: index.js`);
    }

  } catch (error) {
    console.error('\n❌ Build failed:', error.message);
    if (error.errors) {
      console.error('\nBuild errors:');
      error.errors.forEach(err => console.error(`  - ${err.text}`));
    }
    process.exit(1);
  }
}

// Run only as the entrypoint: tests import the Rule A verifier without building.
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  buildHooks();
}