chore: merge upstream v12.5.1 + keep local fixes
Upstream changes (v12.4.7 → v12.5.1): v12.4.8 — timeline tool: coerce stringified numeric anchor in MCP tool (#2176) v12.4.9 — 7 critical fixes (PR #2219): - build/bundle drift fix - strip privacy tags before summarization - preserve relevance order in semantic search - restore Windows spawn + Windows CI - Codex transcript ingestion + Windows queue self-deadlock fix - SDK boundary isolation (closes 6 issues) - standalone batch fixes v12.5.0 — observation pipeline cleanup: - removed per-message retry counter that silently dropped data - parser collapsed to binary {valid:true,...} | {valid:false} - schema migrations v31 + v32 drop dead pending_messages columns: retry_count, failed_at_epoch, completed_at_epoch, worker_pid - status enum reduced to 'pending' | 'processing' - GeneratorExitHandler drain-in-flight loop deleted - PendingMessageStore: 226 → 165 lines (markFailed etc removed) - net -181 lines of source v12.5.1 — install fix for Node 25+ (tree-sitter native build skipped via trustedDependencies allowlist) (#2278) Local fixes preserved (resolved manual conflicts in SessionStore.ts and sessions/create.ts where upstream removed surrounding context): - env-sanitizer PATH extension for claude CLI lookup (auto-merged with upstream's expanded ENV_PRESERVE for AWS Bedrock / Vertex auth vars) - SessionStore + sessions/create stale session reset (mac sleep / 4h wall-clock) Built artifacts rebuilt; both fixes verified present in worker-service.cjs. Worker restarted to v12.5.1 (PID 94088). Schema v31+v32 auto-migration ran on startup. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,16 +1,4 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Bun Runner - Finds and executes Bun even when not in PATH
|
||||
*
|
||||
* This script solves the fresh install problem where:
|
||||
* 1. smart-install.js installs Bun to ~/.bun/bin/bun
|
||||
* 2. But Bun isn't in PATH until terminal restart
|
||||
* 3. Subsequent hooks fail because they can't find `bun`
|
||||
*
|
||||
* Usage: node bun-runner.js <script> [args...]
|
||||
*
|
||||
* Fixes #818: Worker fails to start on fresh install
|
||||
*/
|
||||
import { spawnSync, spawn } from 'child_process';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { join, dirname, resolve } from 'path';
|
||||
@@ -19,20 +7,9 @@ import { fileURLToPath } from 'url';
|
||||
|
||||
const IS_WINDOWS = process.platform === 'win32';
|
||||
|
||||
// Self-resolve plugin root when CLAUDE_PLUGIN_ROOT is not set by Claude Code.
|
||||
// Upstream bug: anthropics/claude-code#24529 — Stop hooks (and on Linux, all hooks)
|
||||
// don't receive CLAUDE_PLUGIN_ROOT, causing script paths to resolve to /scripts/...
|
||||
// which doesn't exist. This fallback derives the plugin root from bun-runner.js's
|
||||
// own filesystem location (this file lives in <plugin-root>/scripts/).
|
||||
const __bun_runner_dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const RESOLVED_PLUGIN_ROOT = process.env.CLAUDE_PLUGIN_ROOT || resolve(__bun_runner_dirname, '..');
|
||||
|
||||
/**
|
||||
* Fix script path arguments that were broken by empty CLAUDE_PLUGIN_ROOT.
|
||||
* When CLAUDE_PLUGIN_ROOT is empty, "${CLAUDE_PLUGIN_ROOT}/scripts/foo.cjs"
|
||||
* expands to "/scripts/foo.cjs" which doesn't exist. Detect this and rewrite
|
||||
* the path using our self-resolved plugin root.
|
||||
*/
|
||||
function fixBrokenScriptPath(argPath) {
|
||||
if (argPath.startsWith('/scripts/') && !existsSync(argPath)) {
|
||||
const fixedPath = join(RESOLVED_PLUGIN_ROOT, argPath);
|
||||
@@ -43,14 +20,7 @@ function fixBrokenScriptPath(argPath) {
|
||||
return argPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find Bun executable - checks PATH first, then common install locations
|
||||
*/
|
||||
function findBun() {
|
||||
// Try PATH first.
|
||||
// On Windows, pass a single command string to avoid Node 22+ DEP0190 deprecation warning
|
||||
// (triggered when an args array is combined with shell:true, as the args are only
|
||||
// concatenated, not escaped). Fixes #1503.
|
||||
const pathCheck = IS_WINDOWS
|
||||
? spawnSync('where bun', {
|
||||
encoding: 'utf-8',
|
||||
@@ -63,19 +33,15 @@ function findBun() {
|
||||
});
|
||||
|
||||
if (pathCheck.status === 0 && pathCheck.stdout.trim()) {
|
||||
// On Windows, prefer bun.cmd over bun (bun is a shell script, bun.cmd is the Windows batch file)
|
||||
if (IS_WINDOWS) {
|
||||
const bunCmdPath = pathCheck.stdout.split('\n').find(line => line.trim().endsWith('bun.cmd'));
|
||||
if (bunCmdPath) {
|
||||
return bunCmdPath.trim();
|
||||
}
|
||||
}
|
||||
return 'bun'; // Found in PATH
|
||||
return 'bun';
|
||||
}
|
||||
|
||||
// Check common installation paths (handles fresh installs before PATH reload)
|
||||
// Windows: Bun installs to ~/.bun/bin/bun.exe (same as smart-install.js)
|
||||
// Unix: Check default location plus common package manager paths
|
||||
const bunPaths = IS_WINDOWS
|
||||
? [join(homedir(), '.bun', 'bin', 'bun.exe')]
|
||||
: [
|
||||
@@ -94,8 +60,6 @@ function findBun() {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Early exit if plugin is disabled in Claude Code settings (#781).
|
||||
// Sync read + JSON parse — fastest possible check before spawning Bun.
|
||||
function isPluginDisabledInClaudeSettings() {
|
||||
try {
|
||||
const configDir = process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude');
|
||||
@@ -112,7 +76,6 @@ if (isPluginDisabledInClaudeSettings()) {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Get args: node bun-runner.js <script> [args...]
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args.length === 0) {
|
||||
@@ -120,7 +83,6 @@ if (args.length === 0) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Fix broken script paths caused by empty CLAUDE_PLUGIN_ROOT (#1215)
|
||||
args[0] = fixBrokenScriptPath(args[0]);
|
||||
|
||||
const bunPath = findBun();
|
||||
@@ -131,14 +93,8 @@ if (!bunPath) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Fix #646: Buffer stdin in Node.js before passing to Bun.
|
||||
// On Linux, Bun's libuv calls fstat() on inherited pipe fds and crashes with
|
||||
// EINVAL when the pipe comes from Claude Code's hook system. By reading stdin
|
||||
// in Node.js first and writing it to a fresh pipe, Bun receives a normal pipe
|
||||
// that it can fstat() without errors.
|
||||
function collectStdin() {
|
||||
return new Promise((resolve) => {
|
||||
// If stdin is a TTY (interactive), there's no piped data to collect
|
||||
if (process.stdin.isTTY) {
|
||||
resolve(null);
|
||||
return;
|
||||
@@ -150,11 +106,9 @@ function collectStdin() {
|
||||
resolve(chunks.length > 0 ? Buffer.concat(chunks) : null);
|
||||
});
|
||||
process.stdin.on('error', () => {
|
||||
// stdin may not be readable (e.g. already closed), treat as no data
|
||||
resolve(null);
|
||||
});
|
||||
|
||||
// Safety: if no data arrives within 5s, proceed without stdin
|
||||
setTimeout(() => {
|
||||
process.stdin.removeAllListeners();
|
||||
process.stdin.pause();
|
||||
@@ -165,10 +119,6 @@ function collectStdin() {
|
||||
|
||||
const stdinData = await collectStdin();
|
||||
|
||||
// Spawn Bun with the provided script and args
|
||||
// Use spawn (not spawnSync) to properly handle stdio
|
||||
// On Windows, use cmd.exe to execute bun.cmd since npm-installed bun is a batch file
|
||||
// Use windowsHide to prevent a visible console window from spawning on Windows
|
||||
const spawnOptions = {
|
||||
stdio: ['pipe', 'inherit', 'inherit'],
|
||||
windowsHide: true,
|
||||
@@ -179,17 +129,14 @@ let spawnCmd = bunPath;
|
||||
let spawnArgs = args;
|
||||
|
||||
if (IS_WINDOWS) {
|
||||
// On Windows, bun.cmd must be executed via cmd /c
|
||||
spawnCmd = 'cmd';
|
||||
spawnArgs = ['/c', bunPath, ...args];
|
||||
const quote = (s) => `"${String(s).replace(/"/g, '\\"')}"`;
|
||||
spawnOptions.shell = true;
|
||||
spawnCmd = [bunPath, ...args].map(quote).join(' ');
|
||||
spawnArgs = [];
|
||||
}
|
||||
|
||||
const child = spawn(spawnCmd, spawnArgs, spawnOptions);
|
||||
|
||||
// Write buffered stdin to child's pipe, then close it so the child sees EOF.
|
||||
// Fall back to '{}' when no stdin data is available so worker-service.cjs
|
||||
// always receives valid JSON input even when Claude Code doesn't pipe stdin
|
||||
// (e.g. during SessionStart on some platforms). Fixes #1560.
|
||||
if (child.stdin) {
|
||||
child.stdin.write(stdinData || '{}');
|
||||
child.stdin.end();
|
||||
@@ -201,9 +148,6 @@ child.on('error', (err) => {
|
||||
});
|
||||
|
||||
child.on('close', (code, signal) => {
|
||||
// Fix #1505: When the "start" subcommand forks a daemon, the parent bun
|
||||
// process may be killed by signal (e.g. SIGKILL, exit code 137). The daemon
|
||||
// is running fine — treat signal-based exits for "start" as success.
|
||||
if ((signal || code > 128) && args.includes('start')) {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,590 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Smart Install Script for claude-mem
|
||||
*
|
||||
* Ensures Bun runtime and uv (Python package manager) are installed
|
||||
* (auto-installs if missing) and handles dependency installation when needed.
|
||||
*
|
||||
* Resolves the install directory from CLAUDE_PLUGIN_ROOT (set by Claude Code
|
||||
* for both cache and marketplace installs), falling back to script location
|
||||
* and legacy paths.
|
||||
*/
|
||||
import { existsSync, readFileSync, writeFileSync, openSync, readSync, closeSync } from 'fs';
|
||||
import { execSync, spawnSync } from 'child_process';
|
||||
import { join, dirname } from 'path';
|
||||
import { homedir } from 'os';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
// Early exit if plugin is disabled in Claude Code settings (#781)
|
||||
function isPluginDisabledInClaudeSettings() {
|
||||
try {
|
||||
const configDir = process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude');
|
||||
const settingsPath = join(configDir, 'settings.json');
|
||||
if (!existsSync(settingsPath)) return false;
|
||||
const settings = JSON.parse(readFileSync(settingsPath, 'utf-8'));
|
||||
return settings?.enabledPlugins?.['claude-mem@thedotmack'] === false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (isPluginDisabledInClaudeSettings()) {
|
||||
process.exit(0);
|
||||
}
|
||||
const IS_WINDOWS = process.platform === 'win32';
|
||||
|
||||
/**
|
||||
* Resolve the plugin root directory where dependencies should be installed.
|
||||
*
|
||||
* Priority:
|
||||
* 1. CLAUDE_PLUGIN_ROOT env var (set by Claude Code for hooks — works for
|
||||
* both cache-based and marketplace installs)
|
||||
* 2. Script location (dirname of this file, up one level from scripts/)
|
||||
* 3. XDG path (~/.config/claude/plugins/marketplaces/thedotmack)
|
||||
* 4. Legacy path (~/.claude/plugins/marketplaces/thedotmack)
|
||||
*/
|
||||
function resolveRoot() {
|
||||
// CLAUDE_PLUGIN_ROOT is the authoritative location set by Claude Code
|
||||
if (process.env.CLAUDE_PLUGIN_ROOT) {
|
||||
const root = process.env.CLAUDE_PLUGIN_ROOT;
|
||||
if (existsSync(join(root, 'package.json'))) return root;
|
||||
}
|
||||
|
||||
// Derive from script location (this file is in <root>/scripts/)
|
||||
try {
|
||||
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||
const candidate = dirname(scriptDir);
|
||||
if (existsSync(join(candidate, 'package.json'))) return candidate;
|
||||
} catch {
|
||||
// import.meta.url not available
|
||||
}
|
||||
|
||||
// Probe XDG path, then legacy
|
||||
const marketplaceRel = join('plugins', 'marketplaces', 'thedotmack');
|
||||
const xdg = join(homedir(), '.config', 'claude', marketplaceRel);
|
||||
if (existsSync(join(xdg, 'package.json'))) return xdg;
|
||||
|
||||
return join(homedir(), '.claude', marketplaceRel);
|
||||
}
|
||||
|
||||
const ROOT = resolveRoot();
|
||||
const MARKER = join(ROOT, '.install-version');
|
||||
|
||||
/**
|
||||
* Check if Bun is installed and accessible
|
||||
*/
|
||||
function isBunInstalled() {
|
||||
try {
|
||||
const result = spawnSync('bun', ['--version'], {
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
shell: IS_WINDOWS
|
||||
});
|
||||
if (result.status === 0) return true;
|
||||
} catch {
|
||||
// PATH check failed, try common installation paths
|
||||
}
|
||||
|
||||
// Check common installation paths (handles fresh installs before PATH reload)
|
||||
const bunPaths = IS_WINDOWS
|
||||
? [join(homedir(), '.bun', 'bin', 'bun.exe')]
|
||||
: [join(homedir(), '.bun', 'bin', 'bun'), '/usr/local/bin/bun', '/opt/homebrew/bin/bun'];
|
||||
|
||||
return bunPaths.some(existsSync);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Bun executable path (from PATH or common install locations)
|
||||
*/
|
||||
function getBunPath() {
|
||||
// Try PATH first
|
||||
try {
|
||||
const result = spawnSync('bun', ['--version'], {
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
shell: IS_WINDOWS
|
||||
});
|
||||
if (result.status === 0) return 'bun';
|
||||
} catch {
|
||||
// Not in PATH
|
||||
}
|
||||
|
||||
// Check common installation paths
|
||||
const bunPaths = IS_WINDOWS
|
||||
? [join(homedir(), '.bun', 'bin', 'bun.exe')]
|
||||
: [join(homedir(), '.bun', 'bin', 'bun'), '/usr/local/bin/bun', '/opt/homebrew/bin/bun'];
|
||||
|
||||
for (const bunPath of bunPaths) {
|
||||
if (existsSync(bunPath)) return bunPath;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimum required bun version
|
||||
* v1.1.14+ required for .changes property and multi-statement SQL support
|
||||
*/
|
||||
const MIN_BUN_VERSION = '1.1.14';
|
||||
|
||||
/**
|
||||
* Compare semver versions
|
||||
*/
|
||||
function compareVersions(v1, v2) {
|
||||
const parts1 = v1.split('.').map(Number);
|
||||
const parts2 = v2.split('.').map(Number);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const p1 = parts1[i] || 0;
|
||||
const p2 = parts2[i] || 0;
|
||||
if (p1 > p2) return 1;
|
||||
if (p1 < p2) return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if bun version meets minimum requirements
|
||||
*/
|
||||
function isBunVersionSufficient() {
|
||||
const version = getBunVersion();
|
||||
if (!version) return false;
|
||||
return compareVersions(version, MIN_BUN_VERSION) >= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Bun version if installed
|
||||
*/
|
||||
function getBunVersion() {
|
||||
const bunPath = getBunPath();
|
||||
if (!bunPath) return null;
|
||||
|
||||
try {
|
||||
const result = spawnSync(bunPath, ['--version'], {
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
shell: IS_WINDOWS
|
||||
});
|
||||
return result.status === 0 ? result.stdout.trim() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if uv is installed and accessible
|
||||
*/
|
||||
function isUvInstalled() {
|
||||
try {
|
||||
const result = spawnSync('uv', ['--version'], {
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
shell: IS_WINDOWS
|
||||
});
|
||||
if (result.status === 0) return true;
|
||||
} catch {
|
||||
// PATH check failed, try common installation paths
|
||||
}
|
||||
|
||||
// Check common installation paths (handles fresh installs before PATH reload)
|
||||
const uvPaths = IS_WINDOWS
|
||||
? [join(homedir(), '.local', 'bin', 'uv.exe'), join(homedir(), '.cargo', 'bin', 'uv.exe')]
|
||||
: [join(homedir(), '.local', 'bin', 'uv'), join(homedir(), '.cargo', 'bin', 'uv'), '/usr/local/bin/uv', '/opt/homebrew/bin/uv'];
|
||||
|
||||
return uvPaths.some(existsSync);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get uv version if installed
|
||||
*/
|
||||
function getUvVersion() {
|
||||
try {
|
||||
const result = spawnSync('uv', ['--version'], {
|
||||
encoding: 'utf-8',
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
shell: IS_WINDOWS
|
||||
});
|
||||
return result.status === 0 ? result.stdout.trim() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Install Bun automatically based on platform
|
||||
*/
|
||||
function installBun() {
|
||||
console.error('🔧 Bun not found. Installing Bun runtime...');
|
||||
|
||||
try {
|
||||
if (IS_WINDOWS) {
|
||||
// Windows: Use PowerShell installer
|
||||
console.error(' Installing via PowerShell...');
|
||||
execSync('powershell -c "irm bun.sh/install.ps1 | iex"', {
|
||||
stdio: ['pipe', 'pipe', 'inherit'],
|
||||
shell: true
|
||||
});
|
||||
} else {
|
||||
// Unix/macOS: Use curl installer
|
||||
console.error(' Installing via curl...');
|
||||
execSync('curl -fsSL https://bun.sh/install | bash', {
|
||||
stdio: ['pipe', 'pipe', 'inherit'],
|
||||
shell: true
|
||||
});
|
||||
}
|
||||
|
||||
// Verify installation
|
||||
if (isBunInstalled()) {
|
||||
const version = getBunVersion();
|
||||
console.error(`✅ Bun ${version} installed successfully`);
|
||||
return true;
|
||||
} else {
|
||||
// Bun may be installed but not in PATH yet for this session
|
||||
// Try common installation paths
|
||||
const bunPaths = IS_WINDOWS
|
||||
? [join(homedir(), '.bun', 'bin', 'bun.exe')]
|
||||
: [join(homedir(), '.bun', 'bin', 'bun'), '/usr/local/bin/bun', '/opt/homebrew/bin/bun'];
|
||||
|
||||
for (const bunPath of bunPaths) {
|
||||
if (existsSync(bunPath)) {
|
||||
console.error(`✅ Bun installed at ${bunPath}`);
|
||||
console.error('⚠️ Please restart your terminal or add Bun to PATH:');
|
||||
if (IS_WINDOWS) {
|
||||
console.error(` $env:Path += ";${join(homedir(), '.bun', 'bin')}"`);
|
||||
} else {
|
||||
console.error(` export PATH="$HOME/.bun/bin:$PATH"`);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Bun installation completed but binary not found');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to install Bun automatically');
|
||||
console.error(' Please install manually:');
|
||||
if (IS_WINDOWS) {
|
||||
console.error(' - winget install Oven-sh.Bun');
|
||||
console.error(' - Or: powershell -c "irm bun.sh/install.ps1 | iex"');
|
||||
} else {
|
||||
console.error(' - curl -fsSL https://bun.sh/install | bash');
|
||||
console.error(' - Or: brew install oven-sh/bun/bun');
|
||||
}
|
||||
console.error(' Then restart your terminal and try again.');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Install uv automatically based on platform
|
||||
*/
|
||||
function installUv() {
|
||||
console.error('🐍 Installing uv for Python/Chroma support...');
|
||||
|
||||
try {
|
||||
if (IS_WINDOWS) {
|
||||
// Windows: Use PowerShell installer
|
||||
console.error(' Installing via PowerShell...');
|
||||
execSync('powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"', {
|
||||
stdio: ['pipe', 'pipe', 'inherit'],
|
||||
shell: true
|
||||
});
|
||||
} else {
|
||||
// Unix/macOS: Use curl installer
|
||||
console.error(' Installing via curl...');
|
||||
execSync('curl -LsSf https://astral.sh/uv/install.sh | sh', {
|
||||
stdio: ['pipe', 'pipe', 'inherit'],
|
||||
shell: true
|
||||
});
|
||||
}
|
||||
|
||||
// Verify installation
|
||||
if (isUvInstalled()) {
|
||||
const version = getUvVersion();
|
||||
console.error(`✅ uv ${version} installed successfully`);
|
||||
return true;
|
||||
} else {
|
||||
// uv may be installed but not in PATH yet for this session
|
||||
// Try common installation paths
|
||||
const uvPaths = IS_WINDOWS
|
||||
? [join(homedir(), '.local', 'bin', 'uv.exe'), join(homedir(), '.cargo', 'bin', 'uv.exe')]
|
||||
: [join(homedir(), '.local', 'bin', 'uv'), join(homedir(), '.cargo', 'bin', 'uv'), '/usr/local/bin/uv', '/opt/homebrew/bin/uv'];
|
||||
|
||||
for (const uvPath of uvPaths) {
|
||||
if (existsSync(uvPath)) {
|
||||
console.error(`✅ uv installed at ${uvPath}`);
|
||||
console.error('⚠️ Please restart your terminal or add uv to PATH:');
|
||||
if (IS_WINDOWS) {
|
||||
console.error(` $env:Path += ";${join(homedir(), '.local', 'bin')}"`);
|
||||
} else {
|
||||
console.error(` export PATH="$HOME/.local/bin:$PATH"`);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('uv installation completed but binary not found');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to install uv automatically');
|
||||
console.error(' Please install manually:');
|
||||
if (IS_WINDOWS) {
|
||||
console.error(' - winget install astral-sh.uv');
|
||||
console.error(' - Or: powershell -c "irm https://astral.sh/uv/install.ps1 | iex"');
|
||||
} else {
|
||||
console.error(' - curl -LsSf https://astral.sh/uv/install.sh | sh');
|
||||
console.error(' - Or: brew install uv (macOS)');
|
||||
}
|
||||
console.error(' Then restart your terminal and try again.');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if dependencies need to be installed
|
||||
*/
|
||||
function needsInstall() {
|
||||
if (!existsSync(join(ROOT, 'node_modules'))) return true;
|
||||
try {
|
||||
const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));
|
||||
const marker = JSON.parse(readFileSync(MARKER, 'utf-8'));
|
||||
return pkg.version !== marker.version || getBunVersion() !== marker.bun;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Install dependencies using Bun with npm fallback
|
||||
*
|
||||
* Bun has issues with npm alias packages (e.g., string-width-cjs, strip-ansi-cjs)
|
||||
* that are defined in package-lock.json. When bun fails with 404 errors for these
|
||||
* packages, we fall back to npm which handles aliases correctly.
|
||||
*/
|
||||
function installDeps() {
|
||||
const bunPath = getBunPath();
|
||||
if (!bunPath) {
|
||||
throw new Error('Bun executable not found');
|
||||
}
|
||||
|
||||
console.error('📦 Installing dependencies with Bun...');
|
||||
|
||||
// Quote path for Windows paths with spaces
|
||||
const bunCmd = IS_WINDOWS && bunPath.includes(' ') ? `"${bunPath}"` : bunPath;
|
||||
|
||||
// Use pipe for stdout to prevent non-JSON output leaking to Claude Code hooks.
|
||||
// stderr is inherited so progress/errors are still visible to the user.
|
||||
const installStdio = ['pipe', 'pipe', 'inherit'];
|
||||
|
||||
let bunSucceeded = false;
|
||||
try {
|
||||
execSync(`${bunCmd} install`, { cwd: ROOT, stdio: installStdio, shell: IS_WINDOWS });
|
||||
bunSucceeded = true;
|
||||
} catch {
|
||||
// First attempt failed, try with force flag
|
||||
try {
|
||||
execSync(`${bunCmd} install --force`, { cwd: ROOT, stdio: installStdio, shell: IS_WINDOWS });
|
||||
bunSucceeded = true;
|
||||
} catch {
|
||||
// Bun failed completely, will try npm fallback
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to npm if bun failed (handles npm alias packages correctly)
|
||||
if (!bunSucceeded) {
|
||||
console.error('⚠️ Bun install failed, falling back to npm...');
|
||||
console.error(' (This can happen with npm alias packages like *-cjs)');
|
||||
try {
|
||||
execSync('npm install --legacy-peer-deps', { cwd: ROOT, stdio: installStdio, shell: IS_WINDOWS });
|
||||
} catch (npmError) {
|
||||
throw new Error('Both bun and npm install failed: ' + npmError.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Write version marker
|
||||
const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));
|
||||
writeFileSync(MARKER, JSON.stringify({
|
||||
version: pkg.version,
|
||||
bun: getBunVersion(),
|
||||
uv: getUvVersion(),
|
||||
installedAt: new Date().toISOString()
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that critical runtime modules are resolvable from the install directory.
|
||||
* Returns true if all critical modules exist, false otherwise.
|
||||
*/
|
||||
function verifyCriticalModules() {
|
||||
const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));
|
||||
const dependencies = Object.keys(pkg.dependencies || {});
|
||||
|
||||
const missing = [];
|
||||
for (const dep of dependencies) {
|
||||
// Check that the module directory exists in node_modules
|
||||
const modulePath = join(ROOT, 'node_modules', ...dep.split('/'));
|
||||
if (!existsSync(modulePath)) {
|
||||
missing.push(dep);
|
||||
}
|
||||
}
|
||||
|
||||
if (missing.length > 0) {
|
||||
console.error(`❌ Post-install check failed: missing modules: ${missing.join(', ')}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Mach-O 64-bit magic values as seen when reading the first 4 file bytes with readUInt32LE.
|
||||
// Native arm64/x86_64 Mach-O files start with bytes [CF FA ED FE]; readUInt32LE gives 0xFEEDFACF.
|
||||
// Byte-swapped (big-endian) Mach-O files start with bytes [FE ED FA CF]; readUInt32LE gives 0xCFFAEDFE.
|
||||
const MACHO_MAGIC_NATIVE = 0xFEEDFACF; // native 64-bit (arm64/x86_64) — file bytes CF FA ED FE
|
||||
const MACHO_MAGIC_SWAPPED = 0xCFFAEDFE; // byte-swapped 64-bit — file bytes FE ED FA CF
|
||||
|
||||
/**
|
||||
* Warn when the bundled claude-mem binary cannot run on the current platform.
|
||||
*
|
||||
* The committed binary (plugin/scripts/claude-mem) is compiled for macOS arm64.
|
||||
* On Linux or Windows it produces "Exec format error" and silently fails.
|
||||
* This check surfaces the incompatibility at install time so users know why
|
||||
* the binary path doesn't work, and confirms the JS fallback (bun-runner.js →
|
||||
* worker-service.cjs) is active and covers all functionality.
|
||||
*
|
||||
* Fixes #1547 — Plugin silently fails on Linux ARM64.
|
||||
*/
|
||||
export function checkBinaryPlatformCompatibility(binaryPath = join(ROOT, 'scripts', 'claude-mem')) {
|
||||
|
||||
if (!existsSync(binaryPath)) {
|
||||
return; // Binary absent — nothing to check (e.g. after npm install which excludes it)
|
||||
}
|
||||
|
||||
// The binary only matters on non-macOS platforms; on macOS it works correctly.
|
||||
if (process.platform === 'darwin') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Read the first 4 bytes to identify the binary format.
|
||||
let fd;
|
||||
try {
|
||||
const buf = Buffer.alloc(4);
|
||||
fd = openSync(binaryPath, 'r');
|
||||
readSync(fd, buf, 0, 4, 0);
|
||||
|
||||
const magic = buf.readUInt32LE(0);
|
||||
if (magic === MACHO_MAGIC_NATIVE || magic === MACHO_MAGIC_SWAPPED) {
|
||||
console.error('⚠️ Platform notice: The bundled claude-mem binary is macOS-only.');
|
||||
console.error(` Current platform: ${process.platform} ${process.arch}`);
|
||||
console.error(' The binary will not execute on this platform.');
|
||||
console.error(' Plugin functionality is provided by the JS fallback');
|
||||
console.error(' (bun-runner.js → worker-service.cjs) which works on all platforms.');
|
||||
}
|
||||
} catch {
|
||||
// Unreadable binary — not critical, skip silently
|
||||
} finally {
|
||||
if (fd !== undefined) closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
// Main execution
|
||||
try {
|
||||
// Step 1: Ensure Bun is installed and meets minimum version (REQUIRED)
|
||||
if (!isBunInstalled()) {
|
||||
installBun();
|
||||
|
||||
// Re-check after installation
|
||||
if (!isBunInstalled()) {
|
||||
console.error('❌ Bun is required but not available in PATH');
|
||||
console.error(' Please restart your terminal after installation');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Step 1.5: Ensure Bun version is sufficient
|
||||
if (!isBunVersionSufficient()) {
|
||||
const currentVersion = getBunVersion();
|
||||
console.error(`⚠️ Bun ${currentVersion} is outdated. Minimum required: ${MIN_BUN_VERSION}`);
|
||||
console.error(' Upgrading bun...');
|
||||
try {
|
||||
execSync('bun upgrade', { stdio: ['pipe', 'pipe', 'inherit'], shell: IS_WINDOWS });
|
||||
if (!isBunVersionSufficient()) {
|
||||
console.error(`❌ Bun upgrade failed. Please manually upgrade: bun upgrade`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.error(`✅ Bun upgraded to ${getBunVersion()}`);
|
||||
} catch (error) {
|
||||
console.error(`❌ Failed to upgrade bun: ${error.message}`);
|
||||
console.error(' Please manually upgrade: bun upgrade');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Step 2: Ensure uv is installed (REQUIRED for vector search)
|
||||
if (!isUvInstalled()) {
|
||||
installUv();
|
||||
|
||||
// Re-check after installation
|
||||
if (!isUvInstalled()) {
|
||||
console.error('❌ uv is required but not available in PATH');
|
||||
console.error(' Please restart your terminal after installation');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3: Install dependencies if needed
|
||||
if (needsInstall()) {
|
||||
const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));
|
||||
const newVersion = pkg.version;
|
||||
|
||||
installDeps();
|
||||
|
||||
// Verify critical modules are resolvable
|
||||
if (!verifyCriticalModules()) {
|
||||
console.error('⚠️ Retrying install with npm...');
|
||||
try {
|
||||
execSync('npm install --production --legacy-peer-deps', { cwd: ROOT, stdio: ['pipe', 'pipe', 'inherit'], shell: IS_WINDOWS });
|
||||
} catch {
|
||||
// npm also failed
|
||||
}
|
||||
if (!verifyCriticalModules()) {
|
||||
console.error('❌ Dependencies could not be installed. Plugin may not work correctly.');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
console.error('✅ Dependencies installed');
|
||||
|
||||
// Auto-restart worker to pick up new code
|
||||
const port = process.env.CLAUDE_MEM_WORKER_PORT || 37777;
|
||||
console.error(`[claude-mem] Plugin updated to v${newVersion} - restarting worker...`);
|
||||
try {
|
||||
// Graceful shutdown via HTTP (curl is cross-platform enough)
|
||||
execSync(`curl -s -X POST http://127.0.0.1:${port}/api/admin/shutdown`, {
|
||||
stdio: 'ignore',
|
||||
shell: IS_WINDOWS,
|
||||
timeout: 5000
|
||||
});
|
||||
// Brief wait for port to free
|
||||
execSync(IS_WINDOWS ? 'timeout /t 1 /nobreak >nul' : 'sleep 0.5', {
|
||||
stdio: 'ignore',
|
||||
shell: true
|
||||
});
|
||||
} catch {
|
||||
// Worker wasn't running or already stopped - that's fine
|
||||
}
|
||||
// Worker will be started fresh by next hook in chain (worker-service.cjs start)
|
||||
}
|
||||
|
||||
// Step 4 (removed in #2054): legacy `claude-mem` shell alias was deleted.
|
||||
// Users invoke the CLI via `npx claude-mem <cmd>` or `bunx claude-mem <cmd>`.
|
||||
|
||||
// Step 5: Warn if the bundled native binary is incompatible with this platform
|
||||
checkBinaryPlatformCompatibility();
|
||||
|
||||
// Output valid JSON for Claude Code hook contract
|
||||
console.log(JSON.stringify({ continue: true, suppressOutput: true }));
|
||||
} catch (e) {
|
||||
console.error('❌ Installation failed:', e.message);
|
||||
// Still output valid JSON so Claude Code doesn't show a confusing error
|
||||
console.log(JSON.stringify({ continue: true, suppressOutput: true }));
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -1,23 +1,4 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* Statusline Counts — lightweight project-scoped observation counter
|
||||
*
|
||||
* Returns JSON with observation and prompt counts for the given project,
|
||||
* suitable for integration into Claude Code's statusLineCommand.
|
||||
*
|
||||
* Usage:
|
||||
* bun statusline-counts.js <cwd>
|
||||
* bun statusline-counts.js /home/user/my-project
|
||||
*
|
||||
* Output (JSON, stdout):
|
||||
* {"observations": 42, "prompts": 15, "project": "my-project"}
|
||||
*
|
||||
* The project name is derived from basename(cwd). Observations are counted
|
||||
* with a WHERE project = ? filter so only the current project's data is
|
||||
* returned — preventing inflated counts from cross-project observations.
|
||||
*
|
||||
* Performance: ~10ms typical (direct SQLite read, no HTTP, no worker dependency)
|
||||
*/
|
||||
import { Database } from "bun:sqlite";
|
||||
import { existsSync, readFileSync } from "fs";
|
||||
import { homedir } from "os";
|
||||
@@ -27,7 +8,6 @@ const cwd = process.argv[2] || process.env.CLAUDE_CWD || process.cwd();
|
||||
const project = basename(cwd);
|
||||
|
||||
try {
|
||||
// Resolve data directory: env var → settings.json → default
|
||||
let dataDir = process.env.CLAUDE_MEM_DATA_DIR || join(homedir(), ".claude-mem");
|
||||
if (!process.env.CLAUDE_MEM_DATA_DIR) {
|
||||
const settingsPath = join(dataDir, "settings.json");
|
||||
@@ -48,7 +28,6 @@ try {
|
||||
const db = new Database(dbPath, { readonly: true });
|
||||
|
||||
const obs = db.query("SELECT COUNT(*) as c FROM observations WHERE project = ?").get(project);
|
||||
// user_prompts links to projects through sdk_sessions.content_session_id
|
||||
const prompts = db.query(
|
||||
`SELECT COUNT(*) as c FROM user_prompts up
|
||||
JOIN sdk_sessions s ON s.content_session_id = up.content_session_id
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env node
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { join, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
function resolveRoot() {
|
||||
if (process.env.CLAUDE_PLUGIN_ROOT) {
|
||||
const root = process.env.CLAUDE_PLUGIN_ROOT;
|
||||
if (existsSync(join(root, 'package.json'))) return root;
|
||||
}
|
||||
try {
|
||||
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||
const candidate = dirname(scriptDir);
|
||||
if (existsSync(join(candidate, 'package.json'))) return candidate;
|
||||
} catch {}
|
||||
return null;
|
||||
}
|
||||
|
||||
const ROOT = resolveRoot();
|
||||
if (!ROOT) process.exit(0);
|
||||
|
||||
try {
|
||||
const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));
|
||||
const markerPath = join(ROOT, '.install-version');
|
||||
if (!existsSync(markerPath)) {
|
||||
console.error('claude-mem: runtime not yet set up — run: npx claude-mem repair');
|
||||
process.exit(0);
|
||||
}
|
||||
const marker = JSON.parse(readFileSync(markerPath, 'utf-8'));
|
||||
if (marker.version !== pkg.version) {
|
||||
console.error(`claude-mem: upgraded to v${pkg.version} — run: npx claude-mem repair`);
|
||||
}
|
||||
} catch {
|
||||
console.error('claude-mem: install marker unreadable — run: npx claude-mem repair');
|
||||
}
|
||||
process.exit(0);
|
||||
+230
-243
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user