mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-12-04 06:21:59 +09:00
fix(helpers): auto-memory hook resolves @claude-flow/memory without a sidecar (#4851)
SessionStart runs auto-memory-hook.mjs directly, and the hook only found @claude-flow/memory through the sidecar that init / upgrade / doctor write. A fresh worktree has no sidecar (.claude-flow/ is gitignored), so imports were DISABLED there. The hook now tries, in order: its own sidecar; the main checkout's sidecar when it runs in a git worktree; the in-repo dist; require.resolve from the helper's install root and from the helper's own directory; and the CLI's own dependencies (@claude-flow/cli, directly or under ruflo / claude-flow), which is where recordMemoryPackagePath() resolves from. Candidates come from MODULE_ROOT or the helper's directory only, never CLAUDE_PROJECT_DIR. A candidate is used only if it exports AutoMemoryBridge. import and sync record the found path in the sidecar, so the next run is fast; status reports where it resolved but writes nothing. When nothing resolves, the existing DISABLED warning now lists every place searched and why each failed. No network, no install. Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
1 parent
29be054e85
commit
724f06e442
3 files changed
+432
-122
No files matched your search
@@ -17,9 +17,10 @@
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, unlinkSync, rmdirSync, rmSync, statSync } from 'fs';
|
||||
import { execFileSync } from 'child_process';
|
||||
import { createRequire } from 'module';
|
||||
import { homedir } from 'os';
|
||||
import { join, dirname, resolve, sep } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { fileURLToPath, pathToFileURL } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
@@ -51,12 +52,13 @@ const dim = (msg) => console.log(` ${DIM}${msg}${RESET}`);
|
||||
// be resolved, self-learning imports are a no-op — the user must see this and be
|
||||
// told exactly how to fix it (on both stdout, so it shows in the Claude Code hook
|
||||
// transcript, and stderr, per the issue's requested channel).
|
||||
function warnMemoryUnavailable() {
|
||||
function warnMemoryUnavailable(searched = []) {
|
||||
const line1 = `[AutoMemory] @claude-flow/memory not resolvable from ${MODULE_ROOT} — self-learning imports are DISABLED.`;
|
||||
const line2 = ' Fix: npm i -D @claude-flow/memory (or re-run: npx ruflo@latest init, then npx ruflo@latest doctor --fix)';
|
||||
console.log(`${YELLOW}${line1}${RESET}`);
|
||||
console.log(`${YELLOW}${line2}${RESET}`);
|
||||
process.stderr.write(`${line1}\n${line2}\n`);
|
||||
// #4851: name every place the resolver looked, so the cause is visible.
|
||||
const lines = [line1, line2, ...(searched.length ? [' Searched:', ...searched.map((s) => ` - ${s}`)] : [])];
|
||||
for (const l of lines) console.log(`${YELLOW}${l}${RESET}`);
|
||||
process.stderr.write(lines.join('\n') + '\n');
|
||||
}
|
||||
|
||||
const DEBUG = !!(process.env.RUFLO_DEBUG || process.env.DEBUG);
|
||||
@@ -361,59 +363,120 @@ class JsonFileBackend {
|
||||
// Resolve memory package path (local dev or npm installed)
|
||||
// ============================================================================
|
||||
|
||||
async function loadMemoryPackage() {
|
||||
// Strategy 0 (#2545): sidecar recorded by `init` / `doctor --fix`. On the
|
||||
// documented `npx ruflo` path @claude-flow/memory (an optionalDependency of
|
||||
// the CLI) lands in the npx cache, which is NOT on the walk-up path from the
|
||||
// project — so init resolves it from the CLI's own context and records the
|
||||
// absolute path here. This is the only strategy that works on that install.
|
||||
try {
|
||||
const sidecar = join(MODULE_ROOT, '.claude-flow', 'memory-package.json');
|
||||
if (existsSync(sidecar)) {
|
||||
const rec = JSON.parse(readFileSync(sidecar, 'utf-8'));
|
||||
if (rec?.distPath && existsSync(rec.distPath)) {
|
||||
return await import(`file://${rec.distPath}`);
|
||||
}
|
||||
}
|
||||
} catch { /* fall through */ }
|
||||
// #4851: SessionStart runs this helper directly, so it must find the package
|
||||
// itself when the sidecar written by init / upgrade / doctor is missing (a
|
||||
// fresh worktree: .claude-flow/ is gitignored) or stale. Every candidate comes
|
||||
// from MODULE_ROOT or the helper's own location, never CLAUDE_PROJECT_DIR, and
|
||||
// is used only if it exports AutoMemoryBridge. No network, no install.
|
||||
const MEMORY_PKG = '@claude-flow/memory';
|
||||
const SIDECAR_PATH = join(MODULE_ROOT, '.claude-flow', 'memory-package.json');
|
||||
// Packages that carry @claude-flow/memory as a dependency; ruflo and
|
||||
// claude-flow reach it through their own @claude-flow/cli.
|
||||
const CLI_HOSTS = [['@claude-flow/cli'], ['ruflo', '@claude-flow/cli'], ['claude-flow', '@claude-flow/cli']];
|
||||
|
||||
// Strategy 1: Local dev (built dist)
|
||||
const localDist = join(MODULE_ROOT, 'v3/@claude-flow/memory/dist/index.js');
|
||||
if (existsSync(localDist)) {
|
||||
try {
|
||||
return await import(`file://${localDist}`);
|
||||
} catch { /* fall through */ }
|
||||
function sidecarDistPath(file) {
|
||||
try {
|
||||
const rec = JSON.parse(readFileSync(file, 'utf-8'));
|
||||
return rec && typeof rec.distPath === 'string' && rec.distPath ? rec.distPath : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
/** require.resolve(spec) as if called from a module in `dir`, or null. */
|
||||
function resolveFrom(dir, spec) {
|
||||
try { return createRequire(join(dir, 'package.json')).resolve(spec); } catch { return null; }
|
||||
}
|
||||
|
||||
/** The package.json of `name` as seen from `dir`: require.resolve, then a node_modules walk-up. */
|
||||
function packageJsonFrom(dir, name) {
|
||||
const viaRequire = resolveFrom(dir, `${name}/package.json`);
|
||||
if (viaRequire) return viaRequire;
|
||||
for (let d = resolve(dir); ; d = dirname(d)) {
|
||||
const candidate = join(d, 'node_modules', ...name.split('/'), 'package.json');
|
||||
if (existsSync(candidate)) return candidate;
|
||||
if (dirname(d) === d) return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Strategy 2: Use createRequire for CJS-style resolution (handles nested node_modules
|
||||
// when installed as a transitive dependency via npx ruflo / npx @claude-flow/cli@latest)
|
||||
try {
|
||||
const { createRequire } = await import('module');
|
||||
const require = createRequire(join(MODULE_ROOT, 'package.json'));
|
||||
return require('@claude-flow/memory');
|
||||
} catch { /* fall through */ }
|
||||
|
||||
// Strategy 3: ESM import (works when @claude-flow/memory is a direct dependency)
|
||||
try {
|
||||
return await import('@claude-flow/memory');
|
||||
} catch { /* fall through */ }
|
||||
|
||||
// Strategy 4: Walk up from MODULE_ROOT looking for @claude-flow/memory in any node_modules
|
||||
let searchDir = MODULE_ROOT;
|
||||
const { parse } = await import('path');
|
||||
while (searchDir !== parse(searchDir).root) {
|
||||
const candidate = join(searchDir, 'node_modules', '@claude-flow', 'memory', 'dist', 'index.js');
|
||||
if (existsSync(candidate)) {
|
||||
try {
|
||||
return await import(`file://${candidate}`);
|
||||
} catch { /* fall through */ }
|
||||
}
|
||||
searchDir = dirname(searchDir);
|
||||
/**
|
||||
* The CLI's own module context, which is where recordMemoryPackagePath()
|
||||
* resolves from: find the installed @claude-flow/cli (directly or under ruflo /
|
||||
* claude-flow) and require.resolve the memory package from there.
|
||||
*/
|
||||
function memoryFromCliPackage(dir) {
|
||||
for (const chain of CLI_HOSTS) {
|
||||
let pkgJson = packageJsonFrom(dir, chain[0]);
|
||||
for (let i = 1; pkgJson && i < chain.length; i++) pkgJson = packageJsonFrom(dirname(pkgJson), chain[i]);
|
||||
const found = pkgJson && resolveFrom(dirname(pkgJson), MEMORY_PKG);
|
||||
if (found) return found;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The resolution strategies, in order; each find() yields a dist path or null. */
|
||||
function memoryCandidates() {
|
||||
const list = [{ source: 'sidecar', label: `sidecar ${SIDECAR_PATH}`, find: () => sidecarDistPath(SIDECAR_PATH) }];
|
||||
// A fresh git worktree has no sidecar of its own, but its main checkout usually does.
|
||||
const main = mainCheckoutRoot(MODULE_ROOT);
|
||||
if (main) {
|
||||
const mainSidecar = join(main, '.claude-flow', 'memory-package.json');
|
||||
list.push({ source: 'main-checkout-sidecar', label: `sidecar ${mainSidecar}`, find: () => sidecarDistPath(mainSidecar) });
|
||||
}
|
||||
const localDist = join(MODULE_ROOT, 'v3/@claude-flow/memory/dist/index.js');
|
||||
list.push(
|
||||
{ source: 'local-dist', label: localDist, find: () => (existsSync(localDist) ? localDist : null) },
|
||||
{ source: 'project-root', label: `require.resolve from ${MODULE_ROOT}`, find: () => resolveFrom(MODULE_ROOT, MEMORY_PKG) },
|
||||
{ source: 'helper-dir', label: `require.resolve from ${__dirname}`, find: () => resolveFrom(__dirname, MEMORY_PKG) },
|
||||
{ source: 'cli-package', label: `@claude-flow/cli dependencies from ${MODULE_ROOT}`, find: () => memoryFromCliPackage(MODULE_ROOT) },
|
||||
{ source: 'cli-package', label: `@claude-flow/cli dependencies from ${__dirname}`, find: () => memoryFromCliPackage(__dirname) },
|
||||
);
|
||||
return list;
|
||||
}
|
||||
|
||||
function memoryPackageVersion(distPath) {
|
||||
try { return JSON.parse(readFileSync(resolve(dirname(distPath), '..', 'package.json'), 'utf-8')).version ?? null; } catch { return null; }
|
||||
}
|
||||
|
||||
/** Same record shape as recordMemoryPackagePath(). Best effort, atomic. */
|
||||
function recordSidecar(distPath) {
|
||||
try {
|
||||
mkdirSync(dirname(SIDECAR_PATH), { recursive: true });
|
||||
const record = { distPath, version: memoryPackageVersion(distPath), resolvedBy: 'auto-memory-hook', resolvedAt: new Date().toISOString() };
|
||||
writeFileAtomic(SIDECAR_PATH, JSON.stringify(record, null, 2));
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns { pkg, distPath, source, searched }. pkg is null when no candidate
|
||||
* exports AutoMemoryBridge, and `searched` then lists every place tried and why
|
||||
* it failed. With record: true, a package found anywhere but this helper's own
|
||||
* sidecar is written to that sidecar, so the next session takes the fast path.
|
||||
*/
|
||||
async function resolveMemoryPackage({ record = false } = {}) {
|
||||
const searched = [];
|
||||
const tried = new Set();
|
||||
for (const c of memoryCandidates()) {
|
||||
let distPath = null;
|
||||
try { distPath = c.find(); } catch { /* treated as not found */ }
|
||||
if (!distPath) { searched.push(`${c.label}: not found`); continue; }
|
||||
if (tried.has(distPath)) continue;
|
||||
tried.add(distPath);
|
||||
if (!existsSync(distPath)) { searched.push(`${c.label}: ${distPath} does not exist`); continue; }
|
||||
let pkg;
|
||||
try { pkg = await import(pathToFileURL(distPath).href); } catch (e) {
|
||||
searched.push(`${c.label}: ${distPath} failed to load (${e && e.message ? e.message : e})`);
|
||||
continue;
|
||||
}
|
||||
if (!pkg || typeof pkg.AutoMemoryBridge !== 'function') {
|
||||
searched.push(`${c.label}: ${distPath} has no AutoMemoryBridge export`);
|
||||
continue;
|
||||
}
|
||||
if (record && c.source !== 'sidecar') recordSidecar(distPath);
|
||||
return { pkg, distPath, source: c.source, searched };
|
||||
}
|
||||
return { pkg: null, distPath: null, source: null, searched };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Read config from .claude-flow/config.yaml
|
||||
// ============================================================================
|
||||
@@ -458,9 +521,9 @@ function readConfig() {
|
||||
async function doImport() {
|
||||
log('Importing auto memory files into bridge...');
|
||||
|
||||
const memPkg = await loadMemoryPackage();
|
||||
if (!memPkg || !memPkg.AutoMemoryBridge) {
|
||||
warnMemoryUnavailable();
|
||||
const { pkg: memPkg, searched } = await resolveMemoryPackage({ record: true });
|
||||
if (!memPkg) {
|
||||
warnMemoryUnavailable(searched);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -544,9 +607,9 @@ async function doSync() {
|
||||
return;
|
||||
}
|
||||
|
||||
const memPkg = await loadMemoryPackage();
|
||||
if (!memPkg || !memPkg.AutoMemoryBridge) {
|
||||
warnMemoryUnavailable();
|
||||
const { pkg: memPkg, searched } = await resolveMemoryPackage({ record: true });
|
||||
if (!memPkg) {
|
||||
warnMemoryUnavailable(searched);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -609,15 +672,16 @@ async function doSync() {
|
||||
}
|
||||
|
||||
async function doStatus() {
|
||||
const memPkg = await loadMemoryPackage();
|
||||
// Read-only: status reports where the package resolves but never records it.
|
||||
const { pkg: memPkg, distPath, source } = await resolveMemoryPackage();
|
||||
const config = readConfig();
|
||||
|
||||
const sidecar = join(MODULE_ROOT, '.claude-flow', 'memory-package.json');
|
||||
const hasSidecar = existsSync(sidecar);
|
||||
const hasSidecar = existsSync(SIDECAR_PATH);
|
||||
|
||||
console.log('\n=== Auto Memory Bridge Status ===\n');
|
||||
console.log(` Package: ${memPkg ? '✅ Available' : '❌ Not found — self-learning DISABLED (fix: npm i -D @claude-flow/memory)'}`);
|
||||
console.log(` Resolver: ${hasSidecar ? '✅ .claude-flow/memory-package.json' : '⏸ no sidecar (run: npx ruflo@latest doctor --fix)'}`);
|
||||
if (memPkg) console.log(` Resolved via: ${source} (${distPath})`);
|
||||
console.log(` Resolver: ${hasSidecar ? '✅ .claude-flow/memory-package.json' : memPkg ? '⏸ no sidecar yet (the next import records one)' : '⏸ no sidecar (run: npx ruflo@latest doctor --fix)'}`);
|
||||
console.log(` Store: ${existsSync(STORE_PATH) ? '✅ ' + STORE_PATH : '⏸ Not initialized'}`);
|
||||
console.log(` LearningBridge: ${config.learningBridge.enabled ? '✅ Enabled' : '⏸ Disabled'}`);
|
||||
console.log(` MemoryGraph: ${config.memoryGraph.enabled ? '✅ Enabled' : '⏸ Disabled'}`);
|
||||
|
||||
@@ -17,9 +17,10 @@
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, unlinkSync, rmdirSync, rmSync, statSync } from 'fs';
|
||||
import { execFileSync } from 'child_process';
|
||||
import { createRequire } from 'module';
|
||||
import { homedir } from 'os';
|
||||
import { join, dirname, resolve, sep } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { fileURLToPath, pathToFileURL } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
@@ -51,12 +52,13 @@ const dim = (msg) => console.log(` ${DIM}${msg}${RESET}`);
|
||||
// be resolved, self-learning imports are a no-op — the user must see this and be
|
||||
// told exactly how to fix it (on both stdout, so it shows in the Claude Code hook
|
||||
// transcript, and stderr, per the issue's requested channel).
|
||||
function warnMemoryUnavailable() {
|
||||
function warnMemoryUnavailable(searched = []) {
|
||||
const line1 = `[AutoMemory] @claude-flow/memory not resolvable from ${MODULE_ROOT} — self-learning imports are DISABLED.`;
|
||||
const line2 = ' Fix: npm i -D @claude-flow/memory (or re-run: npx ruflo@latest init, then npx ruflo@latest doctor --fix)';
|
||||
console.log(`${YELLOW}${line1}${RESET}`);
|
||||
console.log(`${YELLOW}${line2}${RESET}`);
|
||||
process.stderr.write(`${line1}\n${line2}\n`);
|
||||
// #4851: name every place the resolver looked, so the cause is visible.
|
||||
const lines = [line1, line2, ...(searched.length ? [' Searched:', ...searched.map((s) => ` - ${s}`)] : [])];
|
||||
for (const l of lines) console.log(`${YELLOW}${l}${RESET}`);
|
||||
process.stderr.write(lines.join('\n') + '\n');
|
||||
}
|
||||
|
||||
const DEBUG = !!(process.env.RUFLO_DEBUG || process.env.DEBUG);
|
||||
@@ -361,59 +363,120 @@ class JsonFileBackend {
|
||||
// Resolve memory package path (local dev or npm installed)
|
||||
// ============================================================================
|
||||
|
||||
async function loadMemoryPackage() {
|
||||
// Strategy 0 (#2545): sidecar recorded by `init` / `doctor --fix`. On the
|
||||
// documented `npx ruflo` path @claude-flow/memory (an optionalDependency of
|
||||
// the CLI) lands in the npx cache, which is NOT on the walk-up path from the
|
||||
// project — so init resolves it from the CLI's own context and records the
|
||||
// absolute path here. This is the only strategy that works on that install.
|
||||
try {
|
||||
const sidecar = join(MODULE_ROOT, '.claude-flow', 'memory-package.json');
|
||||
if (existsSync(sidecar)) {
|
||||
const rec = JSON.parse(readFileSync(sidecar, 'utf-8'));
|
||||
if (rec?.distPath && existsSync(rec.distPath)) {
|
||||
return await import(`file://${rec.distPath}`);
|
||||
}
|
||||
}
|
||||
} catch { /* fall through */ }
|
||||
// #4851: SessionStart runs this helper directly, so it must find the package
|
||||
// itself when the sidecar written by init / upgrade / doctor is missing (a
|
||||
// fresh worktree: .claude-flow/ is gitignored) or stale. Every candidate comes
|
||||
// from MODULE_ROOT or the helper's own location, never CLAUDE_PROJECT_DIR, and
|
||||
// is used only if it exports AutoMemoryBridge. No network, no install.
|
||||
const MEMORY_PKG = '@claude-flow/memory';
|
||||
const SIDECAR_PATH = join(MODULE_ROOT, '.claude-flow', 'memory-package.json');
|
||||
// Packages that carry @claude-flow/memory as a dependency; ruflo and
|
||||
// claude-flow reach it through their own @claude-flow/cli.
|
||||
const CLI_HOSTS = [['@claude-flow/cli'], ['ruflo', '@claude-flow/cli'], ['claude-flow', '@claude-flow/cli']];
|
||||
|
||||
// Strategy 1: Local dev (built dist)
|
||||
const localDist = join(MODULE_ROOT, 'v3/@claude-flow/memory/dist/index.js');
|
||||
if (existsSync(localDist)) {
|
||||
try {
|
||||
return await import(`file://${localDist}`);
|
||||
} catch { /* fall through */ }
|
||||
function sidecarDistPath(file) {
|
||||
try {
|
||||
const rec = JSON.parse(readFileSync(file, 'utf-8'));
|
||||
return rec && typeof rec.distPath === 'string' && rec.distPath ? rec.distPath : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
/** require.resolve(spec) as if called from a module in `dir`, or null. */
|
||||
function resolveFrom(dir, spec) {
|
||||
try { return createRequire(join(dir, 'package.json')).resolve(spec); } catch { return null; }
|
||||
}
|
||||
|
||||
/** The package.json of `name` as seen from `dir`: require.resolve, then a node_modules walk-up. */
|
||||
function packageJsonFrom(dir, name) {
|
||||
const viaRequire = resolveFrom(dir, `${name}/package.json`);
|
||||
if (viaRequire) return viaRequire;
|
||||
for (let d = resolve(dir); ; d = dirname(d)) {
|
||||
const candidate = join(d, 'node_modules', ...name.split('/'), 'package.json');
|
||||
if (existsSync(candidate)) return candidate;
|
||||
if (dirname(d) === d) return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Strategy 2: Use createRequire for CJS-style resolution (handles nested node_modules
|
||||
// when installed as a transitive dependency via npx ruflo / npx @claude-flow/cli@latest)
|
||||
try {
|
||||
const { createRequire } = await import('module');
|
||||
const require = createRequire(join(MODULE_ROOT, 'package.json'));
|
||||
return require('@claude-flow/memory');
|
||||
} catch { /* fall through */ }
|
||||
|
||||
// Strategy 3: ESM import (works when @claude-flow/memory is a direct dependency)
|
||||
try {
|
||||
return await import('@claude-flow/memory');
|
||||
} catch { /* fall through */ }
|
||||
|
||||
// Strategy 4: Walk up from MODULE_ROOT looking for @claude-flow/memory in any node_modules
|
||||
let searchDir = MODULE_ROOT;
|
||||
const { parse } = await import('path');
|
||||
while (searchDir !== parse(searchDir).root) {
|
||||
const candidate = join(searchDir, 'node_modules', '@claude-flow', 'memory', 'dist', 'index.js');
|
||||
if (existsSync(candidate)) {
|
||||
try {
|
||||
return await import(`file://${candidate}`);
|
||||
} catch { /* fall through */ }
|
||||
}
|
||||
searchDir = dirname(searchDir);
|
||||
/**
|
||||
* The CLI's own module context, which is where recordMemoryPackagePath()
|
||||
* resolves from: find the installed @claude-flow/cli (directly or under ruflo /
|
||||
* claude-flow) and require.resolve the memory package from there.
|
||||
*/
|
||||
function memoryFromCliPackage(dir) {
|
||||
for (const chain of CLI_HOSTS) {
|
||||
let pkgJson = packageJsonFrom(dir, chain[0]);
|
||||
for (let i = 1; pkgJson && i < chain.length; i++) pkgJson = packageJsonFrom(dirname(pkgJson), chain[i]);
|
||||
const found = pkgJson && resolveFrom(dirname(pkgJson), MEMORY_PKG);
|
||||
if (found) return found;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The resolution strategies, in order; each find() yields a dist path or null. */
|
||||
function memoryCandidates() {
|
||||
const list = [{ source: 'sidecar', label: `sidecar ${SIDECAR_PATH}`, find: () => sidecarDistPath(SIDECAR_PATH) }];
|
||||
// A fresh git worktree has no sidecar of its own, but its main checkout usually does.
|
||||
const main = mainCheckoutRoot(MODULE_ROOT);
|
||||
if (main) {
|
||||
const mainSidecar = join(main, '.claude-flow', 'memory-package.json');
|
||||
list.push({ source: 'main-checkout-sidecar', label: `sidecar ${mainSidecar}`, find: () => sidecarDistPath(mainSidecar) });
|
||||
}
|
||||
const localDist = join(MODULE_ROOT, 'v3/@claude-flow/memory/dist/index.js');
|
||||
list.push(
|
||||
{ source: 'local-dist', label: localDist, find: () => (existsSync(localDist) ? localDist : null) },
|
||||
{ source: 'project-root', label: `require.resolve from ${MODULE_ROOT}`, find: () => resolveFrom(MODULE_ROOT, MEMORY_PKG) },
|
||||
{ source: 'helper-dir', label: `require.resolve from ${__dirname}`, find: () => resolveFrom(__dirname, MEMORY_PKG) },
|
||||
{ source: 'cli-package', label: `@claude-flow/cli dependencies from ${MODULE_ROOT}`, find: () => memoryFromCliPackage(MODULE_ROOT) },
|
||||
{ source: 'cli-package', label: `@claude-flow/cli dependencies from ${__dirname}`, find: () => memoryFromCliPackage(__dirname) },
|
||||
);
|
||||
return list;
|
||||
}
|
||||
|
||||
function memoryPackageVersion(distPath) {
|
||||
try { return JSON.parse(readFileSync(resolve(dirname(distPath), '..', 'package.json'), 'utf-8')).version ?? null; } catch { return null; }
|
||||
}
|
||||
|
||||
/** Same record shape as recordMemoryPackagePath(). Best effort, atomic. */
|
||||
function recordSidecar(distPath) {
|
||||
try {
|
||||
mkdirSync(dirname(SIDECAR_PATH), { recursive: true });
|
||||
const record = { distPath, version: memoryPackageVersion(distPath), resolvedBy: 'auto-memory-hook', resolvedAt: new Date().toISOString() };
|
||||
writeFileAtomic(SIDECAR_PATH, JSON.stringify(record, null, 2));
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns { pkg, distPath, source, searched }. pkg is null when no candidate
|
||||
* exports AutoMemoryBridge, and `searched` then lists every place tried and why
|
||||
* it failed. With record: true, a package found anywhere but this helper's own
|
||||
* sidecar is written to that sidecar, so the next session takes the fast path.
|
||||
*/
|
||||
async function resolveMemoryPackage({ record = false } = {}) {
|
||||
const searched = [];
|
||||
const tried = new Set();
|
||||
for (const c of memoryCandidates()) {
|
||||
let distPath = null;
|
||||
try { distPath = c.find(); } catch { /* treated as not found */ }
|
||||
if (!distPath) { searched.push(`${c.label}: not found`); continue; }
|
||||
if (tried.has(distPath)) continue;
|
||||
tried.add(distPath);
|
||||
if (!existsSync(distPath)) { searched.push(`${c.label}: ${distPath} does not exist`); continue; }
|
||||
let pkg;
|
||||
try { pkg = await import(pathToFileURL(distPath).href); } catch (e) {
|
||||
searched.push(`${c.label}: ${distPath} failed to load (${e && e.message ? e.message : e})`);
|
||||
continue;
|
||||
}
|
||||
if (!pkg || typeof pkg.AutoMemoryBridge !== 'function') {
|
||||
searched.push(`${c.label}: ${distPath} has no AutoMemoryBridge export`);
|
||||
continue;
|
||||
}
|
||||
if (record && c.source !== 'sidecar') recordSidecar(distPath);
|
||||
return { pkg, distPath, source: c.source, searched };
|
||||
}
|
||||
return { pkg: null, distPath: null, source: null, searched };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Read config from .claude-flow/config.yaml
|
||||
// ============================================================================
|
||||
@@ -458,9 +521,9 @@ function readConfig() {
|
||||
async function doImport() {
|
||||
log('Importing auto memory files into bridge...');
|
||||
|
||||
const memPkg = await loadMemoryPackage();
|
||||
if (!memPkg || !memPkg.AutoMemoryBridge) {
|
||||
warnMemoryUnavailable();
|
||||
const { pkg: memPkg, searched } = await resolveMemoryPackage({ record: true });
|
||||
if (!memPkg) {
|
||||
warnMemoryUnavailable(searched);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -544,9 +607,9 @@ async function doSync() {
|
||||
return;
|
||||
}
|
||||
|
||||
const memPkg = await loadMemoryPackage();
|
||||
if (!memPkg || !memPkg.AutoMemoryBridge) {
|
||||
warnMemoryUnavailable();
|
||||
const { pkg: memPkg, searched } = await resolveMemoryPackage({ record: true });
|
||||
if (!memPkg) {
|
||||
warnMemoryUnavailable(searched);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -609,15 +672,16 @@ async function doSync() {
|
||||
}
|
||||
|
||||
async function doStatus() {
|
||||
const memPkg = await loadMemoryPackage();
|
||||
// Read-only: status reports where the package resolves but never records it.
|
||||
const { pkg: memPkg, distPath, source } = await resolveMemoryPackage();
|
||||
const config = readConfig();
|
||||
|
||||
const sidecar = join(MODULE_ROOT, '.claude-flow', 'memory-package.json');
|
||||
const hasSidecar = existsSync(sidecar);
|
||||
const hasSidecar = existsSync(SIDECAR_PATH);
|
||||
|
||||
console.log('\n=== Auto Memory Bridge Status ===\n');
|
||||
console.log(` Package: ${memPkg ? '✅ Available' : '❌ Not found — self-learning DISABLED (fix: npm i -D @claude-flow/memory)'}`);
|
||||
console.log(` Resolver: ${hasSidecar ? '✅ .claude-flow/memory-package.json' : '⏸ no sidecar (run: npx ruflo@latest doctor --fix)'}`);
|
||||
if (memPkg) console.log(` Resolved via: ${source} (${distPath})`);
|
||||
console.log(` Resolver: ${hasSidecar ? '✅ .claude-flow/memory-package.json' : memPkg ? '⏸ no sidecar yet (the next import records one)' : '⏸ no sidecar (run: npx ruflo@latest doctor --fix)'}`);
|
||||
console.log(` Store: ${existsSync(STORE_PATH) ? '✅ ' + STORE_PATH : '⏸ Not initialized'}`);
|
||||
console.log(` LearningBridge: ${config.learningBridge.enabled ? '✅ Enabled' : '⏸ Disabled'}`);
|
||||
console.log(` MemoryGraph: ${config.memoryGraph.enabled ? '✅ Enabled' : '⏸ Disabled'}`);
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* Regression for #4851: the SessionStart import runs auto-memory-hook.mjs
|
||||
* directly, and the hook only found @claude-flow/memory through the sidecar
|
||||
* written by init / upgrade / doctor. A fresh worktree has no sidecar
|
||||
* (.claude-flow/ is gitignored), so imports were DISABLED there.
|
||||
*
|
||||
* The hook now resolves the package itself when the sidecar is missing or
|
||||
* stale, verifies the AutoMemoryBridge export, and records the sidecar so the
|
||||
* next run is fast. When nothing resolves, the warning names what it searched.
|
||||
*
|
||||
* Mock-first: the "memory package" is a stub module in a temp dir. No network.
|
||||
*/
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import * as fs from 'node:fs';
|
||||
import { execFileSync, spawnSync } from 'node:child_process';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const packageHook = resolve(here, '../.claude/helpers/auto-memory-hook.mjs');
|
||||
const dogfoodHook = resolve(here, '../../../../.claude/helpers/auto-memory-hook.mjs');
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of tempRoots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const write = (file: string, text: string) => {
|
||||
fs.mkdirSync(dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, text);
|
||||
};
|
||||
|
||||
/** A stub @claude-flow/memory whose bridge stores one entry on import. */
|
||||
const STUB_BRIDGE = `export class AutoMemoryBridge {
|
||||
constructor(backend) { this.backend = backend; }
|
||||
async importFromAutoMemory() {
|
||||
await this.backend.store({ id: 'stub-1', key: 'stub', namespace: 'auto-memory', content: 'x', type: 'semantic', tags: [], metadata: {}, createdAt: 1, updatedAt: 1 });
|
||||
return { imported: 1, skipped: 0 };
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
function plantMemoryPackage(pkgDir: string, body = STUB_BRIDGE): string {
|
||||
write(join(pkgDir, 'package.json'), JSON.stringify({ name: '@claude-flow/memory', version: '9.9.9-stub', type: 'module', main: 'dist/index.js', exports: { '.': './dist/index.js' } }));
|
||||
const dist = join(pkgDir, 'dist', 'index.js');
|
||||
write(dist, body);
|
||||
return fs.realpathSync(dist);
|
||||
}
|
||||
|
||||
function plantPackage(dir: string, name: string) {
|
||||
write(join(dir, 'package.json'), JSON.stringify({ name, version: '1.0.0', type: 'module', main: 'index.js' }));
|
||||
}
|
||||
|
||||
/** A project with the hook installed the way init does, and no sidecar. */
|
||||
function project(source: string) {
|
||||
const root = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), 'ruflo-4851-')));
|
||||
tempRoots.push(root);
|
||||
const dir = join(root, 'project');
|
||||
const home = join(root, 'home');
|
||||
fs.mkdirSync(home, { recursive: true });
|
||||
write(join(dir, 'package.json'), JSON.stringify({ name: 'repro-4851', version: '1.0.0' }));
|
||||
const hook = join(dir, '.claude', 'helpers', 'auto-memory-hook.mjs');
|
||||
write(hook, fs.readFileSync(source, 'utf8'));
|
||||
return { root, dir, home, hook, sidecar: join(dir, '.claude-flow', 'memory-package.json') };
|
||||
}
|
||||
|
||||
function run(hook: string, cwd: string, home: string, cmd: string) {
|
||||
const env: NodeJS.ProcessEnv = { ...process.env, HOME: home, USERPROFILE: home, CLAUDE_PROJECT_DIR: cwd };
|
||||
delete env.NODE_PATH; // pnpm's vitest shim would otherwise expose the workspace package
|
||||
const r = spawnSync(process.execPath, [hook, cmd], { cwd, env, encoding: 'utf8', timeout: 20_000 });
|
||||
expect(r.error).toBeUndefined();
|
||||
return { status: r.status, stdout: r.stdout, stderr: r.stderr };
|
||||
}
|
||||
|
||||
const readSidecar = (file: string) => JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
|
||||
for (const [name, source] of [['package', packageHook], ['repository', dogfoodHook]] as const) {
|
||||
describe(`#4851 ${name} helper resolves @claude-flow/memory without a sidecar`, () => {
|
||||
it('fresh worktree: no sidecar, package resolvable from the project → import works and the sidecar is written', () => {
|
||||
const p = project(source);
|
||||
const dist = plantMemoryPackage(join(p.dir, 'node_modules', '@claude-flow', 'memory'));
|
||||
expect(fs.existsSync(p.sidecar)).toBe(false);
|
||||
|
||||
const r = run(p.hook, p.dir, p.home, 'import');
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.stdout).toContain('Imported 1 entries');
|
||||
expect(r.stdout).not.toContain('DISABLED');
|
||||
expect(readSidecar(p.sidecar)).toMatchObject({ distPath: dist, version: '9.9.9-stub', resolvedBy: 'auto-memory-hook' });
|
||||
|
||||
// The second run takes the sidecar and leaves it untouched.
|
||||
const before = fs.readFileSync(p.sidecar, 'utf8');
|
||||
expect(run(p.hook, p.dir, p.home, 'import').stdout).toContain('Imported 1 entries');
|
||||
expect(fs.readFileSync(p.sidecar, 'utf8')).toBe(before);
|
||||
});
|
||||
|
||||
it("finds the package in the CLI's own node_modules, as recordMemoryPackagePath does", () => {
|
||||
const p = project(source);
|
||||
const cli = join(p.dir, 'node_modules', 'ruflo', 'node_modules', '@claude-flow', 'cli');
|
||||
plantPackage(join(p.dir, 'node_modules', 'ruflo'), 'ruflo');
|
||||
plantPackage(cli, '@claude-flow/cli');
|
||||
const dist = plantMemoryPackage(join(cli, 'node_modules', '@claude-flow', 'memory'));
|
||||
|
||||
const r = run(p.hook, p.dir, p.home, 'import');
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.stdout).toContain('Imported 1 entries');
|
||||
expect(readSidecar(p.sidecar).distPath).toBe(dist);
|
||||
});
|
||||
|
||||
it("fresh git worktree: uses the main checkout's sidecar and records its own", () => {
|
||||
const p = project(source);
|
||||
const dist = plantMemoryPackage(join(p.root, 'elsewhere', '@claude-flow', 'memory'));
|
||||
write(join(p.dir, '.gitignore'), '.claude-flow/\n');
|
||||
const git = (...args: string[]) => execFileSync('git', args, { cwd: p.dir, stdio: 'ignore', env: { ...process.env, HOME: p.home, GIT_CONFIG_NOSYSTEM: '1' } });
|
||||
git('init', '-q', '-b', 'main');
|
||||
git('add', '.');
|
||||
git('-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-m', 'init');
|
||||
write(p.sidecar, JSON.stringify({ distPath: dist, resolvedBy: 'init' }));
|
||||
const wt = join(p.root, 'wt');
|
||||
git('worktree', 'add', '-q', wt);
|
||||
const wtHook = join(wt, '.claude', 'helpers', 'auto-memory-hook.mjs');
|
||||
const wtSidecar = join(wt, '.claude-flow', 'memory-package.json');
|
||||
expect(fs.existsSync(wtSidecar)).toBe(false);
|
||||
|
||||
const r = run(wtHook, wt, p.home, 'import');
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.stdout).toContain('Imported 1 entries');
|
||||
expect(readSidecar(wtSidecar).distPath).toBe(dist);
|
||||
});
|
||||
|
||||
it('stale sidecar (missing file) → re-resolved and rewritten', () => {
|
||||
const p = project(source);
|
||||
const dist = plantMemoryPackage(join(p.dir, 'node_modules', '@claude-flow', 'memory'));
|
||||
write(p.sidecar, JSON.stringify({ distPath: join(p.root, 'gone', 'dist', 'index.js'), resolvedBy: 'init' }));
|
||||
|
||||
const r = run(p.hook, p.dir, p.home, 'import');
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.stdout).toContain('Imported 1 entries');
|
||||
expect(readSidecar(p.sidecar)).toMatchObject({ distPath: dist, resolvedBy: 'auto-memory-hook' });
|
||||
});
|
||||
|
||||
it('stale sidecar (module without AutoMemoryBridge) → re-resolved and rewritten', () => {
|
||||
const p = project(source);
|
||||
const dist = plantMemoryPackage(join(p.dir, 'node_modules', '@claude-flow', 'memory'));
|
||||
const wrong = plantMemoryPackage(join(p.root, 'old', 'memory'), 'export const somethingElse = 1;\n');
|
||||
write(p.sidecar, JSON.stringify({ distPath: wrong, resolvedBy: 'init' }));
|
||||
|
||||
const r = run(p.hook, p.dir, p.home, 'import');
|
||||
expect(r.stdout).toContain('Imported 1 entries');
|
||||
expect(readSidecar(p.sidecar).distPath).toBe(dist);
|
||||
});
|
||||
|
||||
it('nothing resolvable → the disabled warning names every place searched, and no sidecar is written', () => {
|
||||
const p = project(source);
|
||||
const wrong = plantMemoryPackage(join(p.root, 'old', 'memory'), 'export const somethingElse = 1;\n');
|
||||
write(p.sidecar, JSON.stringify({ distPath: wrong }));
|
||||
|
||||
const r = run(p.hook, p.dir, p.home, 'import');
|
||||
expect(r.status).toBe(0); // loud but non-fatal, as before
|
||||
expect(r.stdout).toContain('self-learning imports are DISABLED');
|
||||
expect(r.stdout).toContain('npm i -D @claude-flow/memory');
|
||||
expect(r.stdout).toContain('Searched:');
|
||||
expect(r.stdout).toContain(`sidecar ${p.sidecar}: ${wrong} has no AutoMemoryBridge export`);
|
||||
expect(r.stdout).toContain(`require.resolve from ${p.dir}: not found`);
|
||||
expect(r.stdout).toContain(`require.resolve from ${join(p.dir, '.claude', 'helpers')}: not found`);
|
||||
expect(r.stdout).toContain(`@claude-flow/cli dependencies from ${p.dir}: not found`);
|
||||
expect(r.stderr).toContain('Searched:');
|
||||
expect(readSidecar(p.sidecar)).toEqual({ distPath: wrong }); // left as it was
|
||||
expect(fs.existsSync(join(p.dir, '.claude-flow', 'data', 'auto-memory-store.json'))).toBe(false);
|
||||
});
|
||||
|
||||
it('status reports the resolution but never writes the sidecar', () => {
|
||||
const p = project(source);
|
||||
plantMemoryPackage(join(p.dir, 'node_modules', '@claude-flow', 'memory'));
|
||||
const r = run(p.hook, p.dir, p.home, 'status');
|
||||
expect(r.status).toBe(0);
|
||||
expect(r.stdout).toContain('Package: ✅ Available');
|
||||
expect(r.stdout).toContain('Resolved via: project-root');
|
||||
expect(fs.existsSync(p.sidecar)).toBe(false);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user