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
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
/**
* Shared Claude executable discovery and validation.
*
* Used by SDKAgent and KnowledgeAgent to locate a working Claude Code CLI.
*
* Every candidate is probed with the CAPABILITY PROBE — `--permission-mode
* dontAsk --version` — not just `--version`. claude-mem passes
* `--permission-mode dontAsk` on every Observer/KnowledgeAgent spawn (see
* buildHardenedSdkOptions in src/sdk/hardened-options.ts), and CLIs older than
* the 2.1.x line reject it with "argument 'dontAsk' is invalid" and exit 1
* before doing any work. A binary that answers `--version` but fails the probe
* would die instantly at SDK spawn time, producing the silent
* "healthy worker, zero observations" failure mode (#2782 family; previously
* #1857/#2049 with --setting-sources, #1866, #2142). The probe makes no API
* call: a capable CLI short-circuits on --version (~150 ms), an incompatible
* one errors at flag parsing.
*
* When several candidates are installed (PATH shadowing, abandoned npm-global
* installs next to the auto-updating native installer), the NEWEST capable
* version wins — PATH order is only a tie-breaker.
*
* Closes #2222 (desktop-app detection), hardens against stale-CLI selection.
*/
import { exec, execFile } from 'child_process';
import { promisify } from 'util';
import { existsSync, realpathSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
import { isCurrentDirectoryCandidate, isWindowsNativeExecutable, windowsWhereExecutablePath } from './spawn.js';
import { SettingsDefaultsManager } from './SettingsDefaultsManager.js';
import { USER_SETTINGS_PATH, expandTilde } from './paths.js';
import { logger, type Component } from '../utils/logger.js';
import { withNpmClaudeExe } from './windows-npm-claude.js';
/**
* How long to wait for a probe (`--version` / capability) before giving up (ms).
*
* The native `claude` binary is large (~225 MB) and a cold start on Windows
* (first run after install, antivirus real-time scan) can take several seconds.
* A too-tight timeout makes a perfectly good CLI look unusable, which on a
* Windows npm-global path then surfaces as a misleading "desktop app" error.
* Warm probes return in ~0.5 s, so 10 s only bites on cold starts.
*/
const VERSION_CHECK_TIMEOUT_MS = 10_000;
/**
* The flags every Observer/KnowledgeAgent spawn passes that old CLIs reject.
* MUST stay in sync with buildHardenedSdkOptions (src/sdk/hardened-options.ts):
* if a new always-on SDK option maps to a CLI flag old binaries don't know,
* add it here so the resolver rejects those binaries up front instead of
* letting every spawn die with exit 1.
*
* `--version` terminates the invocation without any API call once the flags
* before it parse cleanly.
*/
export const CAPABILITY_PROBE_ARGS = ['--permission-mode', 'dontAsk', '--version'] as const;
/**
* Successful resolutions are cached briefly: findClaudeExecutable() runs once
* per SDK query, and each cold resolution costs one subprocess spawn per
* installed candidate. Failures are never cached, so a user who updates their
* CLI is picked up on the next observation without a worker restart. A cached
* resolution only answers for the CLAUDE_CODE_PATH it was made under, so
* changing that setting takes effect on the next call too.
*/
const RESOLUTION_CACHE_TTL_MS = 15 * 60_000;
interface CachedResolution {
path: string;
version: string;
/** The CLAUDE_CODE_PATH setting this was resolved under ('' when discovered). */
configuredSetting: string;
expiresAtMs: number;
}
let cachedResolution: CachedResolution | null = null;
/** Concurrent cache misses for the same setting share one set of CLI probes. */
const pendingResolutions = new Map<string, Promise<string>>();
/** Test hook: clear the resolution cache between cases. */
export function resetClaudeExecutableCache(): void {
cachedResolution = null;
pendingResolutions.clear();
}
/**
* Seam for unit tests — probing and discovery shell out to real binaries,
* which tests replace by reassigning these members (no module mocking).
*/
export const _internals = {
exec: promisify(exec),
execFile: promisify(execFile),
existsSync,
realpathSync,
homedir,
platform: (): NodeJS.Platform => process.platform,
loadSettings: () => SettingsDefaultsManager.loadFromFile(USER_SETTINGS_PATH),
};
/**
* A Claude CLI binary exists on disk at a discovered path but this worker
* process can no longer spawn it (ENOENT on posix_spawn despite the file
* being present — typically a stale worker after Claude Code's native
* auto-updater swapped the binary underneath a long-running process).
*
* Carries every present-but-unspawnable candidate plus the probe detail, so
* callers can surface a single actionable error rather than a generic
* not-found. The message deliberately includes the literal token `ENOENT` so
* `classifyClaudeError` keeps mapping it to `setup_required` — but the
* `isClaudeExecutableUnspawnable` discriminator lets the routes layer
* distinguish it from a genuine setup gap and trigger a self-heal restart.
*/
export class ClaudeExecutableUnspawnableError extends Error {
readonly candidates: ReadonlyArray<{ path: string; detail: string }>;
constructor(candidates: ReadonlyArray<{ path: string; detail: string }>) {
const list = candidates.map(c => ` - ${c.path} — ${c.detail}`).join('\n');
super(
'Claude executable(s) exist on disk but could not be spawned by this worker process ' +
'(ENOENT on posix_spawn despite the file being present — typically a stale worker after a ' +
`Claude Code CLI auto-update):\n${list}\n` +
`Restarting the worker resolves this. ${updateInstructions()}`
);
this.name = 'ClaudeExecutableUnspawnableError';
this.candidates = candidates;
}
}
export function isClaudeExecutableUnspawnable(err: unknown): err is ClaudeExecutableUnspawnableError {
return err instanceof ClaudeExecutableUnspawnableError;
}
/**
* Returns true if the path looks like a Windows desktop-app installation
* (AppData or Program Files) rather than a CLI installed via npm/volta/etc.
*/
function looksLikeDesktopAppPath(candidatePath: string): boolean {
const normalized = candidatePath.replace(/\\/g, '/').toLowerCase();
// npm / Node CLI installs on Windows live under %AppData%\Roaming\npm\node_modules\…
// — the exact location `npm install -g @anthropic-ai/claude-code` uses. Those contain
// "appdata" but are NOT the desktop app; treating them as such tells users to reinstall
// the CLI they already have. Bail out for any npm/node_modules path first. (See #2723.)
if (normalized.includes('/node_modules/') || normalized.includes('/npm/')) {
return false;
}
return (
normalized.includes('appdata') ||
normalized.includes('program files') ||
normalized.includes('program files (x86)')
);
}
type ProbeResult =
/** Runs and accepts every flag claude-mem passes. */
| { kind: 'capable'; version: string }
/** Runs (`--version` works) but rejects the capability flags — too old. */
| { kind: 'incompatible'; version: string; detail: string }
/**
* Does not resolve to a usable CLI. `launchFailed` is true only when the OS
* could not start the process at all (desktop app, missing interpreter,
* corrupt install); false when the process ran but failed its version probe
* (non-zero exit, timeout, or no version output).
*/
| { kind: 'broken'; detail: string; launchFailed: boolean };
/**
* Run `<candidate> <args>` without blocking the worker while the CLI starts.
*
* Uses asynchronous execFile so the candidate path is passed as a
* separate argument and never interpreted by a shell. This prevents shell
* injection if the path contains characters like `"`, `;`, `&` — reachable
* on Windows via a crafted CLAUDE_CODE_PATH in settings.json.
*/
async function runProbe(candidate: string, args: readonly string[]): Promise<{ stdout: string } | { error: string; flagRejection: boolean; launchFailed: boolean }> {
try {
const { stdout } = await _internals.execFile(candidate, [...args], {
encoding: 'utf8',
timeout: VERSION_CHECK_TIMEOUT_MS,
windowsHide: true,
});
return { stdout: stdout.trim() };
} catch (error) {
const err = error as { stderr?: unknown; code?: unknown; signal?: unknown; killed?: unknown };
const stderrText = String(err.stderr ?? '').trim();
const firstLine = (stderrText || (error instanceof Error ? error.message : String(error)))
.split('\n')[0]
.trim();
// A genuine flag rejection is the ONLY proof a CLI is too old: it ran to
// argument parsing, wrote a diagnostic to stderr, and exited non-zero.
// A timeout or signal kill (killed/signal set, empty stderr — a Windows
// cold start losing the 10 s race) leaves no such proof, so it must stay
// retryable and never classify as incompatible.
const status = err.code;
const killed = err.killed === true;
const signalled = err.signal != null;
const flagRejection = stderrText.length > 0 && !killed && !signalled && typeof status === 'number' && status !== 0;
// Did the OS fail to launch the process at all (ENOENT/EACCES/ENOEXEC), or
// did the process run and then fail? A launch failure yields neither a
// numeric exit code nor a termination signal — the child never started. A
// non-zero exit sets a numeric `code`; a timeout sets `signal`/`killed`. Only a
// true launch failure is the "found but could not be executed" case.
const launchFailed = typeof status !== 'number' && err.signal == null && !err.killed;
// Probe failures are expected classification signals (stale CLI, desktop
// app, broken install); callers warn on or surface the detail, so this
// stays at debug with the full error for deep troubleshooting.
logger.debug('SDK', `Probe of "${candidate}" failed: ${firstLine || 'probe failed'}`, { args: [...args], flagRejection, launchFailed }, error);
return { error: firstLine || 'probe failed', flagRejection, launchFailed };
}
}
/**
* Probe one candidate. A capable CLI is classified in a single spawn
* (capability flags + --version). Only when that probe fails does a second
* plain `--version` spawn run, to split "runs but too old" from "doesn't run
* at all" without pattern-matching stderr wording — so the two-spawn cost is
* paid only for stale/broken installs, and the result is cached.
*
* A capability probe that failed WITHOUT flag-rejection evidence (empty
* stderr from a timeout or signal kill) is not proof of an old CLI: on a
* Windows cold start the first spawn can lose the 10 s race, then the now-warm
* plain `--version` returns instantly — which must NOT read as "runs but too
* old". So after `--version` warms the binary, the capability probe runs once
* more; only real flag rejection classifies the CLI as incompatible.
*/
async function probeCandidate(candidate: string): Promise<ProbeResult> {
const capability = await runProbe(candidate, CAPABILITY_PROBE_ARGS);
if ('stdout' in capability && capability.stdout) {
return { kind: 'capable', version: capability.stdout };
}
// Capability probe failed. Distinguish "runs but rejects our flags" (old
// CLI) from "doesn't run at all" (desktop app, broken install) via a plain
// --version. Any error wording ("invalid", "unknown option", localized
// variants) classifies the same way, so no stderr pattern-matching.
const plain = await runProbe(candidate, ['--version']);
if ('stdout' in plain && plain.stdout) {
if ('flagRejection' in capability && capability.flagRejection) {
return { kind: 'incompatible', version: plain.stdout, detail: capability.error };
}
// No flag-rejection evidence: the capability probe most likely lost a
// cold-start race that the --version spawn just warmed away. Re-probe the
// warm binary once before giving up.
const warm = await runProbe(candidate, CAPABILITY_PROBE_ARGS);
if ('stdout' in warm && warm.stdout) {
return { kind: 'capable', version: warm.stdout };
}
if ('flagRejection' in warm && warm.flagRejection) {
return { kind: 'incompatible', version: plain.stdout, detail: warm.error };
}
// Still no flag-rejection proof, only ambiguous failures. Use the binary
// rather than throw the misleading "too old" error and strand a CLI that
// answers --version; a genuinely old CLI rejects the flag with a non-empty
// stderr, which the checks above already catch.
return { kind: 'capable', version: plain.stdout };
}
const detail = 'error' in capability ? capability.error : 'failed --version check';
// The plain --version is the last word on whether this binary can launch:
// if it errored on a spawn failure, so did the capability probe (same
// binary); if it exited cleanly with no output, `launchFailed` is absent
// (it ran, it just gave no version), so default to false.
const launchFailed = 'launchFailed' in plain ? plain.launchFailed : false;
return { kind: 'broken', detail, launchFailed };
}
/** Parse "2.1.176 (Claude Code)" → [2, 1, 176]; unparseable sorts lowest. */
function parseVersionKey(version: string): [number, number, number] {
const match = version.match(/(\d+)\.(\d+)\.(\d+)/);
if (!match) return [0, 0, 0];
return [Number(match[1]), Number(match[2]), Number(match[3])];
}
function compareVersionKeysDesc(a: [number, number, number], b: [number, number, number]): number {
return b[0] - a[0] || b[1] - a[1] || b[2] - a[2];
}
/**
* All places a Claude CLI might live, best-effort and deduplicated:
* - every PATH match (`which -a` / `where`), not just the first — a stale
* binary earlier in PATH must not hide a current one later in PATH
* - the native installer's symlink (~/.local/bin/claude) and the legacy
* local-install location (~/.claude/local/claude), which may not be on the
* worker's PATH at all depending on how the daemon was spawned
*
* Order is preserved (PATH order first) and only used to break version ties.
*/
async function discoverCandidates(): Promise<string[]> {
const candidates: string[] = [];
if (_internals.platform() === 'win32') {
// Gather every PATH hit through where.exe argv (not a shell string), so the
// lookup does not flash a console and names with spaces stay argv-safe.
// `claude` already lists the native binary and any shim (PATHEXT covers
// .exe and .cmd); `claude.cmd` is kept so a shim on a PATH entry the bare
// lookup misses is still found. Native-before-shim preference is applied
// after dedupe below.
for (const name of ['claude', 'claude.cmd']) {
try {
// where.exe itself must come from System32, and its results exclude
// the current directory — hooks run with the user's project as cwd,
// where a planted claude.exe would otherwise be found and spawned.
const { stdout: output } = await _internals.execFile(windowsWhereExecutablePath(), [name], {
encoding: 'utf8',
windowsHide: true,
});
// where.exe writes the console's active code page (cp949 on ko-KR) but
// the `encoding: 'utf8'` above decodes the bytes as UTF-8, so a
// non-ASCII profile folder name arrives as U+FFFD and the reported
// path does not exist (#4694, #3865). Keep only lines that resolve on
// disk — a garbled candidate would only die at the probe with ENOENT.
candidates.push(
...output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean)
.filter((line) => !isCurrentDirectoryCandidate(line))
.filter((line) => _internals.existsSync(line)),
);
} catch {
// Not found via this lookup — try the next discovery source.
}
}
// A global npm install's PATH hits are shims the SDK can't spawn: swap in
// the package's own claude.exe and drop the extension-less sh script.
candidates.splice(0, candidates.length, ...withNpmClaudeExe(candidates, (path) => _internals.existsSync(path)));
// The native installer puts the CLI at ~/.local/bin/claude.exe (and the
// legacy local install at ~/.claude/local/claude.exe), which may not be on
// the worker's PATH at all — or where.exe may only report garbled lines
// (#4694). Without these, a perfectly installed CLI wedges the worker in
// setup_required. The .exe suffix matters: Windows has no shebang, so an
// extension-less file is not spawnable here.
for (const knownPath of [
join(_internals.homedir(), '.local', 'bin', 'claude.exe'),
join(_internals.homedir(), '.claude', 'local', 'claude.exe'),
]) {
if (_internals.existsSync(knownPath)) {
candidates.push(knownPath);
}
}
} else {
try {
const { stdout: output } = await _internals.exec('which -a claude', {
encoding: 'utf8',
windowsHide: true,
});
candidates.push(...output.split('\n').map((line) => line.trim()).filter(Boolean));
} catch {
// which -a found nothing — known install locations below still apply.
}
for (const knownPath of [
join(_internals.homedir(), '.local', 'bin', 'claude'),
join(_internals.homedir(), '.claude', 'local', 'claude'),
]) {
if (_internals.existsSync(knownPath)) {
candidates.push(knownPath);
}
}
}
// Dedupe literal paths, then symlink targets (PATH often repeats dirs, and
// several entries may point at the same real binary).
const seenPaths = new Set<string>();
const seenRealPaths = new Set<string>();
const deduped: string[] = [];
for (const candidate of candidates) {
if (seenPaths.has(candidate)) continue;
seenPaths.add(candidate);
let realPath = candidate;
try {
realPath = _internals.realpathSync(candidate);
} catch {
// Dangling symlink or permission issue — keep the literal path; the
// probe will classify it as broken.
}
if (seenRealPaths.has(realPath)) continue;
seenRealPaths.add(realPath);
deduped.push(candidate);
}
// The agent SDK spawns this path directly on the field-compression calls the
// observer makes with no cmd.exe wrapper, and modern Node refuses to launch a
// .cmd/.bat shim without a shell (EINVAL). When a native .exe/.com and a shim
// resolve to the same install, hand back the native one so the SDK never gets
// a shim it cannot spawn. Stable native-first tie-break only: the newest
// capable version still wins over it (see findClaudeExecutable), sharing the
// native-vs-shim rule with selectWindowsCommandCandidate.
if (_internals.platform() === 'win32') {
deduped.sort((a, b) => Number(isWindowsNativeExecutable(b)) - Number(isWindowsNativeExecutable(a)));
}
return deduped;
}
/**
* Describe a configured CLAUDE_CODE_PATH for an error message without ambiguity.
*
* Telemetry scrubbing rewrites the home directory to `~` before an error
* reaches error tracking (see redactHomeDir in
* src/services/telemetry/error-scrub.ts), so a real absolute path such as
* /home/user/.local/bin/claude arrives tildified and looks exactly like a
* literal `~` the user typed into settings — the tilde bug already fixed in
* find-claude-executable (expandTilde below). Stating whether the value is the
* raw setting or the tilde-expanded one stops a redacted `~` from being read as
* a settings `~`, so the next person does not re-fix a fixed bug.
*/
function describeConfiguredPath(rawSetting: string, expandedPath: string): string {
if (rawSetting === expandedPath) {
return `"${rawSetting}" (used verbatim, no tilde expansion)`;
}
return `"${rawSetting}" (tilde-expanded to "${expandedPath}")`;
}
function updateInstructions(): string {
return (
'Update it (`claude update`, or `npm install -g @anthropic-ai/claude-code@latest` for npm installs), ' +
'remove stale duplicate installs, or set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json to a current CLI.'
);
}
/**
* Find and validate a Claude Code CLI executable.
*
* Discovery order:
* 1. `CLAUDE_CODE_PATH` from settings.json (explicit user override — wins,
* but fails loud if it is too old rather than dying silently at spawn)
* 2. Every `claude` on PATH plus known install locations, probed for
* capability; the newest capable version is returned
*
* @param logComponent Logger {@link Component} tag (e.g. 'SDK', 'WORKER')
* @throws {Error} when no Claude CLI compatible with claude-mem can be found
*/
export async function findClaudeExecutable(logComponent: Component = 'SDK'): Promise<string> {
const settings = _internals.loadSettings();
const configuredSetting = settings.CLAUDE_CODE_PATH || '';
if (
cachedResolution &&
cachedResolution.configuredSetting === configuredSetting &&
cachedResolution.expiresAtMs > Date.now() &&
_internals.existsSync(cachedResolution.path)
) {
return cachedResolution.path;
}
cachedResolution = null;
const pending = pendingResolutions.get(configuredSetting);
if (pending) return pending;
const resolution = resolveClaudeExecutable(configuredSetting, logComponent);
pendingResolutions.set(configuredSetting, resolution);
try {
return await resolution;
} finally {
// Do not retain a failed resolution: installing/updating the CLI must
// take effect on the next call. A cache reset may have started a new one.
if (pendingResolutions.get(configuredSetting) === resolution) pendingResolutions.delete(configuredSetting);
}
}
async function resolveClaudeExecutable(configuredSetting: string, logComponent: Component): Promise<string> {
// --- 1. Explicit configured path ----------------------------------------
if (configuredSetting) {
// A user who types `~/.local/bin/claude` in settings.json expects the shell
// convention, but nothing here runs through a shell — existsSync and
// posix_spawn take the string verbatim, so a literal `~` fails with ENOENT.
// Expand it defensively at read time so both the existence check and every
// probe spawn see a real absolute path (SettingsRoutes also normalizes on
// write; this covers files edited by hand).
const configuredPath = expandTilde(configuredSetting, _internals.homedir());
const describedPath = describeConfiguredPath(configuredSetting, configuredPath);
if (!_internals.existsSync(configuredPath)) {
throw new Error(
`CLAUDE_CODE_PATH is set to ${describedPath} but the file does not exist.`
);
}
const probe = await probeCandidate(configuredPath);
if (probe.kind === 'capable') {
logger.info(logComponent, `Using configured CLAUDE_CODE_PATH: ${configuredPath} (${probe.version})`);
cachedResolution = {
path: configuredPath,
version: probe.version,
configuredSetting,
expiresAtMs: Date.now() + RESOLUTION_CACHE_TTL_MS,
};
return configuredPath;
}
if (probe.kind === 'incompatible') {
throw new Error(
`CLAUDE_CODE_PATH is set to ${describedPath} (${probe.version}) but that CLI is too old for claude-mem — ` +
`it rejects flags every memory agent spawn requires (${probe.detail}). ${updateInstructions()}`
);
}
if (looksLikeDesktopAppPath(configuredPath)) {
throw new Error(
`Found desktop app at ${describedPath} but it doesn't support headless mode. ` +
`Install Claude Code CLI: npm install -g @anthropic-ai/claude-code`
);
}
// existsSync passed above, so the file is really there — the probe failed.
// Split the two ways that happens. A launch failure (ENOENT from a launcher
// whose shebang interpreter is missing, or a native-installer stub pointing
// at a deleted version directory) means the OS never ran the file; a
// re-check of the path cannot fix it, so name the likely cause. A process
// that ran but exited non-zero, timed out, or printed no version is a
// different problem — do not claim it "could not be executed".
if (probe.launchFailed) {
// Present on disk (existsSync guard above) but the OS could not launch
// it — the same stale-worker signature as the discovered-candidate path
// (#3290). Pinned installs must surface the self-heal discriminator too,
// or a wedged CLAUDE_CODE_PATH parks the worker in setup_required
// forever; the launch-failure guidance rides in the candidate detail.
throw new ClaudeExecutableUnspawnableError([
{
path: configuredPath,
detail:
`CLAUDE_CODE_PATH is set to ${describedPath} — the file exists but could not be executed (${probe.detail}). ` +
`A launcher script whose interpreter (shebang) is missing, or a native-installer stub pointing at a deleted version directory, fails this way. ` +
`Reinstall the Claude Code CLI or point CLAUDE_CODE_PATH at a working binary.`,
},
]);
}
throw new Error(
`CLAUDE_CODE_PATH is set to ${describedPath} — the file ran but failed its version probe (${probe.detail}). ` +
`It may be the wrong program, or a wrapper that errors before printing a version. ` +
`Ensure CLAUDE_CODE_PATH points at a working Claude Code CLI binary.`
);
}
// --- 2. Probe every discovered candidate ---------------------------------
const capable: Array<{ path: string; version: string; key: [number, number, number]; order: number }> = [];
const incompatible: Array<{ path: string; version: string; detail: string }> = [];
// Candidates that are present on disk but every probe failed (broken/ENOENT).
// When this set is non-empty AND nothing capable was found, the final throw
// is a ClaudeExecutableUnspawnableError so callers can self-heal restart
// instead of looping forever in setup_required cooldown.
const presentButUnspawnable: Array<{ path: string; detail: string }> = [];
const candidates = await discoverCandidates();
for (let order = 0; order < candidates.length; order++) {
const candidate = candidates[order];
const probe = await probeCandidate(candidate);
if (probe.kind === 'capable') {
capable.push({ path: candidate, version: probe.version, key: parseVersionKey(probe.version), order });
continue;
}
if (probe.kind === 'incompatible') {
incompatible.push({ path: candidate, version: probe.version, detail: probe.detail });
logger.warn(
logComponent,
`Skipping "${candidate}" (${probe.version}) — too old for claude-mem: ${probe.detail}`
);
continue;
}
if (looksLikeDesktopAppPath(candidate)) {
logger.warn(
logComponent,
`Skipping desktop app at "${candidate}" — it doesn't support headless mode. ` +
`Install Claude Code CLI: npm install -g @anthropic-ai/claude-code`
);
} else {
logger.warn(logComponent, `Skipping "${candidate}" — failed --version check (${probe.detail})`);
// A file that is present on disk but the OS could not launch is the
// signature of a stale worker after a CLI auto-update — collected here
// so the final throw can be a ClaudeExecutableUnspawnableError (which
// callers use to self-heal restart) instead of a generic not-found.
// Two guards, both load-bearing: launchFailed because a candidate that
// RAN but failed its version probe is a wrong program, not a stale
// spawn — a restart can never fix it, so it must not burn the self-heal
// budget (matches the configured-path branch); existsSync because a
// MISSING file also probes as launchFailed (spawn ENOENT sets no status
// or signal) and a dangling PATH entry is the genuine not-found case.
if (probe.launchFailed && _internals.existsSync(candidate)) {
presentButUnspawnable.push({ path: candidate, detail: probe.detail });
}
}
}
if (capable.length > 0) {
capable.sort((a, b) => compareVersionKeysDesc(a.key, b.key) || a.order - b.order);
const winner = capable[0];
// INFO, not DEBUG: when observations silently stop, which binary the
// worker picked is the first question — make it answerable from default logs.
logger.info(logComponent, `Using Claude CLI v${winner.version} at ${winner.path}`, {
candidatesProbed: candidates.length,
skippedTooOld: incompatible.length,
});
cachedResolution = {
path: winner.path,
version: winner.version,
configuredSetting,
expiresAtMs: Date.now() + RESOLUTION_CACHE_TTL_MS,
};
return winner.path;
}
if (incompatible.length > 0) {
const lines = incompatible
.map((entry) => ` - ${entry.path} (${entry.version}) — ${entry.detail}`)
.join('\n');
throw new Error(
`Every Claude CLI found is too old for claude-mem (each rejects flags the memory agent passes on every spawn):\n` +
`${lines}\n${updateInstructions()}`
);
}
if (presentButUnspawnable.length > 0) {
throw new ClaudeExecutableUnspawnableError(presentButUnspawnable);
}
throw new Error(
'Claude executable not found. Please either:\n' +
'1. Add "claude" to your system PATH, or\n' +
'2. Set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json'
);
}