Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(init): wire self-learning memory bridge on the npx path (#2545) (#2564)

rUv46228841d4b0
diff --git a/ruflo/README.md b/ruflo/README.md
index bddc8522a5..f275aa771c 100644
--- a/ruflo/README.md
+++ b/ruflo/README.md
@@ -191,6 +191,23 @@ npm install -g ruflo@latest
claude mcp add ruflo -- npx ruflo@latest mcp start
```
+### Start the Background Daemon (enables self-learning + workers)
+
+The 12 background workers (audit, optimize, testgaps, map, document, …) run under
+the daemon. `init` sets everything up but does **not** start it β€” run this once so
+learning and the workers are actually live:
+
+```bash
+# Start the background worker daemon
+npx ruflo@latest daemon start
+
+# Verify everything is wired (learning bridge, daemon, memory, MCP)
+npx ruflo@latest doctor --fix
+```
+
+> πŸ’‘ `doctor --fix` also repairs the self-learning bridge if `@claude-flow/memory`
+> could not be resolved on the `npx` install path (#2545).
+
---
## What You Get
diff --git a/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs b/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs
index 94c4574147..e0764c25cf 100755
--- a/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs
+++ b/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs
@@ -27,10 +27,23 @@ const CYAN = '\x1b[0;36m';
const DIM = '\x1b[2m';
const RESET = '\x1b[0m';
+const YELLOW = '\x1b[0;33m';
const log = (msg) => console.log(`${CYAN}[AutoMemory] ${msg}${RESET}`);
const success = (msg) => console.log(`${GREEN}[AutoMemory] βœ“ ${msg}${RESET}`);
const dim = (msg) => console.log(` ${DIM}${msg}${RESET}`);
+// #2545: fail LOUD instead of a silent dim skip. When @claude-flow/memory cannot
+// 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() {
+ const line1 = `[AutoMemory] @claude-flow/memory not resolvable from ${PROJECT_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`);
+}
+
const DEBUG = !!(process.env.RUFLO_DEBUG || process.env.DEBUG);
// ── Graceful shutdown (FIX 3) ───────────────────────────────────────────────
@@ -152,6 +165,21 @@ class JsonFileBackend {
// ============================================================================
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(PROJECT_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 */ }
+
// Strategy 1: Local dev (built dist)
const localDist = join(PROJECT_ROOT, 'v3/@claude-flow/memory/dist/index.js');
if (existsSync(localDist)) {
@@ -235,7 +263,7 @@ async function doImport() {
const memPkg = await loadMemoryPackage();
if (!memPkg || !memPkg.AutoMemoryBridge) {
- dim('Memory package not available β€” skipping auto memory import');
+ warnMemoryUnavailable();
return;
}
@@ -288,7 +316,7 @@ async function doSync() {
const memPkg = await loadMemoryPackage();
if (!memPkg || !memPkg.AutoMemoryBridge) {
- dim('Memory package not available β€” skipping sync');
+ warnMemoryUnavailable();
return;
}
@@ -346,8 +374,12 @@ async function doStatus() {
const memPkg = await loadMemoryPackage();
const config = readConfig();
+ const sidecar = join(PROJECT_ROOT, '.claude-flow', 'memory-package.json');
+ const hasSidecar = existsSync(sidecar);
+
console.log('\n=== Auto Memory Bridge Status ===\n');
- console.log(` Package: ${memPkg ? 'βœ… Available' : '❌ Not found'}`);
+ 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)'}`);
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'}`);
diff --git a/v3/@claude-flow/cli/__tests__/init-memory-package-resolver-2545.test.ts b/v3/@claude-flow/cli/__tests__/init-memory-package-resolver-2545.test.ts
new file mode 100644
index 0000000000..758de164a1
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/init-memory-package-resolver-2545.test.ts
@@ -0,0 +1,131 @@
+/**
+ * #2545 β€” Documented `npx ruflo init` path leaves self-learning silently
+ * non-functional because `@claude-flow/memory` (an optionalDependency of the
+ * CLI) lands in the npx cache, unreachable by a node_modules walk-up from the
+ * user's project. The SessionStart auto-memory hook then no-op'd with no signal.
+ *
+ * Fix: init resolves the package from the CLI's own module context and records
+ * its absolute path in `.claude-flow/memory-package.json`; the hook reads that
+ * sidecar first. When the package is genuinely unresolvable, the hook now fails
+ * LOUD instead of a silent dim skip.
+ *
+ * These tests pin all three behaviors:
+ * 1. the resolver records + reads back a working sidecar (the "make it work" path)
+ * 2. the deployed hook activates when the sidecar is present (was silent before)
+ * 3. the deployed hook fails LOUD when memory is unresolvable (was silent before)
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ mkdtempSync,
+ mkdirSync,
+ writeFileSync,
+ existsSync,
+ readFileSync,
+ rmSync,
+ copyFileSync,
+} from 'fs';
+import { tmpdir } from 'os';
+import path from 'path';
+import { execFileSync } from 'child_process';
+import { fileURLToPath } from 'url';
+
+import {
+ MEMORY_SIDECAR_REL,
+ resolveMemoryPackageFromCli,
+ resolveMemoryPackageFromProject,
+ recordMemoryPackagePath,
+} from '../src/init/memory-package-resolver.js';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const HOOK_SRC = path.resolve(__dirname, '../.claude/helpers/auto-memory-hook.mjs');
+
+/** Deploy the real init-copied hook into a temp project, like `ruflo init` does. */
+function scaffoldProject(root: string): string {
+ const helpers = path.join(root, '.claude', 'helpers');
+ mkdirSync(helpers, { recursive: true });
+ copyFileSync(HOOK_SRC, path.join(helpers, 'auto-memory-hook.mjs'));
+ writeFileSync(
+ path.join(root, 'package.json'),
+ JSON.stringify({ name: 'repro-2545', version: '1.0.0' }),
+ );
+ return path.join(helpers, 'auto-memory-hook.mjs');
+}
+
+function runHook(hookPath: string, cwd: string, cmd: string): { stdout: string; ok: boolean } {
+ try {
+ const stdout = execFileSync('node', [hookPath, cmd], { cwd, encoding: 'utf-8' });
+ return { stdout, ok: true };
+ } catch (err) {
+ // The hook must never crash Claude Code (exit 0); a throw here is a failure.
+ const e = err as { stdout?: string };
+ return { stdout: e.stdout ?? '', ok: false };
+ }
+}
+
+describe('#2545 memory package resolver', () => {
+ let tmp: string;
+ beforeEach(() => {
+ tmp = mkdtempSync(path.join(tmpdir(), 'cf-2545-'));
+ });
+ afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+ });
+
+ it('resolves @claude-flow/memory from the CLI module context', () => {
+ // In the monorepo this mirrors the npx-cache situation: the package is
+ // reachable from the CLI even though it is not in the user project.
+ const dist = resolveMemoryPackageFromCli();
+ expect(dist).toBeTruthy();
+ expect(existsSync(dist as string)).toBe(true);
+ });
+
+ it('records a resolver sidecar and reads it back (the strategy the hook uses)', () => {
+ const rec = recordMemoryPackagePath(tmp, 'init');
+ expect(rec).toBeTruthy();
+
+ const sidecar = path.join(tmp, MEMORY_SIDECAR_REL);
+ expect(existsSync(sidecar)).toBe(true);
+
+ const parsed = JSON.parse(readFileSync(sidecar, 'utf-8'));
+ expect(parsed.distPath).toBe(rec!.distPath);
+ expect(parsed.resolvedBy).toBe('init');
+
+ // project-side resolution (what doctor + the hook do) finds it via the sidecar
+ expect(resolveMemoryPackageFromProject(tmp)).toBe(rec!.distPath);
+ });
+
+ it('returns null for an isolated project with no package and no sidecar', () => {
+ const nowhere = path.join(tmp, 'isolated', 'deep');
+ mkdirSync(nowhere, { recursive: true });
+ expect(resolveMemoryPackageFromProject(nowhere)).toBeNull();
+ });
+
+ it('deployed hook ACTIVATES self-learning when init has recorded the sidecar', () => {
+ const dist = resolveMemoryPackageFromCli();
+ if (!dist || !existsSync(dist)) {
+ // Built memory dist required for this integration assertion.
+ return;
+ }
+ const hookPath = scaffoldProject(tmp);
+ recordMemoryPackagePath(tmp, 'init'); // what init now does after writeHelpers
+
+ const { stdout, ok } = runHook(hookPath, tmp, 'status');
+ expect(ok).toBe(true); // exit 0 β€” never crashes Claude Code
+ expect(stdout).toContain('Package: βœ… Available');
+ expect(stdout).toContain('Resolver: βœ…');
+ expect(stdout).not.toContain('DISABLED');
+ });
+
+ it('deployed hook fails LOUD (not a silent skip) when memory is unresolvable', () => {
+ const hookPath = scaffoldProject(tmp); // NO sidecar, NO installed package
+
+ const { stdout, ok } = runHook(hookPath, tmp, 'import');
+ expect(ok).toBe(true); // still exit 0 β€” loud, but non-fatal
+ // The pre-fix behavior was a dim "skipping" line with no remediation. Now:
+ expect(stdout).toContain('self-learning imports are DISABLED');
+ expect(stdout).toContain('npm i -D @claude-flow/memory');
+ // and it must NOT create the store (proves it really was a no-op, loudly)
+ expect(existsSync(path.join(tmp, '.claude-flow', 'data', 'auto-memory-store.json'))).toBe(false);
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/doctor.ts b/v3/@claude-flow/cli/src/commands/doctor.ts
index c939a855ed..884f112524 100644
--- a/v3/@claude-flow/cli/src/commands/doctor.ts
+++ b/v3/@claude-flow/cli/src/commands/doctor.ts
@@ -15,6 +15,11 @@ import { execSync, exec } from 'child_process';
import { promisify } from 'util';
import { decodeKey, isEncryptionEnabled } from '../encryption/vault.js';
import { isEncryptedBlob } from '../encryption/vault.js';
+import {
+ resolveMemoryPackageFromProject,
+ readMemoryPackageVersion,
+ recordMemoryPackagePath,
+} from '../init/memory-package-resolver.js';
// Promisified exec with proper shell and env inheritance for cross-platform support
const execAsync = promisify(exec);
@@ -267,6 +272,41 @@ async function checkMemoryDatabase(): Promise<HealthCheck> {
return { name: 'Memory Database', status: 'warn', message: 'Not initialized', fix: 'claude-flow memory configure --backend hybrid' };
}
+// #2545: Check that the self-learning bridge can actually load @claude-flow/memory
+// the SAME way the SessionStart auto-memory hook does. On the documented `npx ruflo`
+// path the package lands in the npx cache β€” unreachable from the project β€” so the
+// hook silently no-op'd with no signal anywhere. This surfaces it.
+async function checkLearningBridge(): Promise<HealthCheck> {
+ const cwd = process.cwd();
+ const hookPath = join(cwd, '.claude', 'helpers', 'auto-memory-hook.mjs');
+
+ // Only relevant once init has deployed the hook; otherwise stay quiet.
+ if (!existsSync(hookPath)) {
+ return {
+ name: 'Learning Bridge',
+ status: 'pass',
+ message: 'auto-memory hook not installed (run: npx ruflo@latest init)',
+ };
+ }
+
+ const distPath = resolveMemoryPackageFromProject(cwd);
+ if (distPath) {
+ const version = readMemoryPackageVersion(distPath);
+ return {
+ name: 'Learning Bridge',
+ status: 'pass',
+ message: `@claude-flow/memory resolvable${version ? ` (v${version})` : ''}`,
+ };
+ }
+
+ return {
+ name: 'Learning Bridge',
+ status: 'fail',
+ message: '@claude-flow/memory NOT resolvable β€” SessionStart self-learning imports are a silent no-op',
+ fix: 'npx ruflo@latest doctor --fix (records resolver sidecar) β€” or: npm i -D @claude-flow/memory',
+ };
+}
+
// Check API keys
async function checkApiKeys(): Promise<HealthCheck> {
const keys = ['ANTHROPIC_API_KEY', 'CLAUDE_API_KEY', 'OPENAI_API_KEY'];
@@ -1084,6 +1124,7 @@ export const doctorCommand: Command = {
checkStaleSettingsNpx, // #2448 β€” runaway `npx @latest` in statusLine/hooks
checkDaemonStatus,
checkMemoryDatabase,
+ checkLearningBridge, // #2545 β€” can the auto-memory hook actually load @claude-flow/memory?
checkApiKeys,
checkMcpServers,
checkAIDefence, // #1807
@@ -1106,6 +1147,8 @@ export const doctorCommand: Command = {
'stale-settings': checkStaleSettingsNpx, // #2448
'daemon': checkDaemonStatus,
'memory': checkMemoryDatabase,
+ 'learning': checkLearningBridge, // #2545
+ 'learning-bridge': checkLearningBridge, // #2545
'api': checkApiKeys,
'git': checkGit,
'mcp': checkMcpServers,
@@ -1161,6 +1204,26 @@ export const doctorCommand: Command = {
output.writeln(output.error('Failed to run health checks'));
}
+ // #2545: --fix / --install can actually repair the Learning Bridge by
+ // recording the resolver sidecar. When doctor runs via `npx ruflo`, the CLI
+ // CAN resolve its optional @claude-flow/memory dep (it is in the same npx
+ // cache), so writing the sidecar makes the SessionStart hook find it.
+ if ((showFix || autoInstall)) {
+ const lbResult = results.find(r => r.name === 'Learning Bridge');
+ if (lbResult && lbResult.status === 'fail') {
+ const record = recordMemoryPackagePath(process.cwd(), 'doctor');
+ if (record) {
+ const newCheck = await checkLearningBridge();
+ const idx = results.findIndex(r => r.name === 'Learning Bridge');
+ if (idx !== -1) results[idx] = newCheck;
+ const fixIdx = fixes.findIndex(f => f.startsWith('Learning Bridge:'));
+ if (fixIdx !== -1 && newCheck.status === 'pass') fixes.splice(fixIdx, 1);
+ output.writeln(output.success(`Repaired Learning Bridge β€” wrote .claude-flow/memory-package.json β†’ ${record.distPath}`));
+ output.writeln(formatCheck(newCheck));
+ }
+ }
+ }
+
// Auto-install missing dependencies if requested
if (autoInstall) {
const claudeCodeResult = results.find(r => r.name === 'Claude Code CLI');
diff --git a/v3/@claude-flow/cli/src/init/executor.ts b/v3/@claude-flow/cli/src/init/executor.ts
index 853bc08ecb..76efa0585a 100644
--- a/v3/@claude-flow/cli/src/init/executor.ts
+++ b/v3/@claude-flow/cli/src/init/executor.ts
@@ -29,6 +29,7 @@ import {
generateRufloHookCjs,
} from './helpers-generator.js';
import { generateClaudeMd } from './claudemd-generator.js';
+import { recordMemoryPackagePath } from './memory-package-resolver.js';
/**
* Skills to copy based on configuration
@@ -223,6 +224,17 @@ export async function executeInit(options: InitOptions): Promise<InitResult> {
// Generate helpers
if (options.components.helpers) {
await writeHelpers(targetDir, options, result);
+
+ // #2545: The auto-memory hook needs @claude-flow/memory, which is an
+ // optionalDependency of the CLI and lands in the npx cache β€” unreachable
+ // by a node_modules walk-up from the user's project. Resolve it from the
+ // CLI's own context now (where it IS present) and record the absolute
+ // path in a machine-local sidecar the hook reads first. Best-effort:
+ // when the optional dep is absent the hook fails loud and doctor flags it.
+ const memRecord = recordMemoryPackagePath(targetDir, 'init');
+ if (memRecord) {
+ result.created.files.push('.claude-flow/memory-package.json');
+ }
}
// Generate statusline
@@ -527,6 +539,13 @@ export async function executeUpgrade(targetDir: string, upgradeSettings = false)
}
}
+ // #2545: (re)record the resolved @claude-flow/memory path so the auto-memory
+ // hook can find it on the npx install path. Best-effort β€” see executeInit.
+ const memRecord = recordMemoryPackagePath(targetDir, 'upgrade');
+ if (memRecord) {
+ result.updated.push('.claude-flow/memory-package.json');
+ }
+
// 1. ALWAYS update statusline helper (force overwrite)
const statuslinePath = path.join(targetDir, '.claude', 'helpers', 'statusline.cjs');
// Use default options with statusline config
diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.ts
index cd84d10074..12978b1ff9 100644
--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts
+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts
@@ -875,13 +875,37 @@ const DATA_DIR = join(PROJECT_ROOT, '.claude-flow', 'data');
const STORE_PATH = join(DATA_DIR, 'auto-memory-store.json');
const DIM = '\\x1b[2m';
+const YELLOW = '\\x1b[0;33m';
const RESET = '\\x1b[0m';
const dim = (msg) => console.log(\` \${DIM}\${msg}\${RESET}\`);
+// #2545: fail LOUD instead of a silent dim skip when @claude-flow/memory is
+// unresolvable β€” self-learning imports are a no-op and the user must be told.
+function warnMemoryUnavailable() {
+ const l1 = \`[AutoMemory] @claude-flow/memory not resolvable from \${PROJECT_ROOT} β€” self-learning imports are DISABLED.\`;
+ const l2 = ' Fix: npm i -D @claude-flow/memory (or re-run: npx ruflo@latest init, then npx ruflo@latest doctor --fix)';
+ console.log(\`\${YELLOW}\${l1}\${RESET}\`);
+ console.log(\`\${YELLOW}\${l2}\${RESET}\`);
+ process.stderr.write(\`\${l1}\\n\${l2}\\n\`);
+}
+
// Ensure data dir
if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });
async function loadMemoryPackage() {
+ // Strategy 0 (#2545): sidecar recorded by \`init\` / \`doctor --fix\`. On the npx
+ // path @claude-flow/memory lands in the npx cache (unreachable by walk-up), so
+ // init records its absolute path here β€” the only strategy that works there.
+ try {
+ const sidecar = join(PROJECT_ROOT, '.claude-flow', 'memory-package.json');
+ if (existsSync(sidecar)) {
+ const rec = JSON.parse(readFileSync(sidecar, 'utf-8'));
+ if (rec && rec.distPath && existsSync(rec.distPath)) {
+ return await import(\`file://\${rec.distPath}\`);
+ }
+ }
+ } catch { /* fall through */ }
+
// Strategy 1: Use createRequire for CJS-style resolution (handles nested node_modules
// when installed as a transitive dependency via npx ruflo / npx claude-flow)
try {
@@ -911,7 +935,7 @@ async function doImport() {
const memPkg = await loadMemoryPackage();
if (!memPkg || !memPkg.AutoMemoryBridge) {
- dim('Memory package not available β€” auto memory import skipped (non-critical)');
+ warnMemoryUnavailable();
return;
}
@@ -928,7 +952,7 @@ async function doSync() {
const memPkg = await loadMemoryPackage();
if (!memPkg || !memPkg.AutoMemoryBridge) {
- dim('Memory package not available β€” sync skipped (non-critical)');
+ warnMemoryUnavailable();
return;
}
diff --git a/v3/@claude-flow/cli/src/init/memory-package-resolver.ts b/v3/@claude-flow/cli/src/init/memory-package-resolver.ts
new file mode 100644
index 0000000000..8a6062016a
--- /dev/null
+++ b/v3/@claude-flow/cli/src/init/memory-package-resolver.ts
@@ -0,0 +1,137 @@
+/**
+ * Memory Package Resolver (#2545)
+ *
+ * `@claude-flow/memory` is an *optionalDependency* of `@claude-flow/cli`. On the
+ * documented `npx ruflo` install path it lands in the npx cache
+ * (`~/.npm/_npx/<hash>/node_modules`), which is NOT on the node_modules walk-up
+ * path from the user's project. The SessionStart auto-memory hook therefore
+ * could never resolve it and self-learning silently no-op'd.
+ *
+ * At init time, however, the CLI *can* resolve the package from its own module
+ * context (it is installed alongside the CLI in that same npx cache). We resolve
+ * it once and record the absolute path in a machine-local project sidecar
+ * (`.claude-flow/memory-package.json`). The hook reads this sidecar first, so it
+ * reuses the copy npx already downloaded β€” no second install, no vendoring.
+ *
+ * This module is deliberately dependency-free and best-effort: nothing here ever
+ * throws into the init/doctor flow.
+ */
+
+import { createRequire } from 'module';
+import * as fs from 'fs';
+import * as path from 'path';
+
+export const MEMORY_PACKAGE = '@claude-flow/memory';
+/** Project-relative path of the resolver sidecar written by init / doctor --fix. */
+export const MEMORY_SIDECAR_REL = path.join('.claude-flow', 'memory-package.json');
+
+export interface MemoryPackageRecord {
+ /** Absolute path to the package's main entry (dist/index.js). */
+ distPath: string;
+ /** Resolved package version, if readable. */
+ version: string | null;
+ /** What produced this record ("init" | "doctor" | "upgrade"). */
+ resolvedBy: string;
+ /** ISO timestamp of resolution. */
+ resolvedAt: string;
+}
+
+/**
+ * Resolve `@claude-flow/memory`'s main entry from the CLI's own module context.
+ * Returns the absolute dist path, or null when the optional dependency is absent
+ * (e.g. installed with `--omit=optional`).
+ */
+export function resolveMemoryPackageFromCli(): string | null {
+ try {
+ const require = createRequire(import.meta.url);
+ return require.resolve(MEMORY_PACKAGE);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Resolve `@claude-flow/memory` the same way the runtime hook does, from a target
+ * project directory: sidecar β†’ project package.json β†’ node_modules walk-up.
+ * Used by `doctor` so its verdict matches what the hook will actually experience.
+ */
+export function resolveMemoryPackageFromProject(targetDir: string): string | null {
+ // 1. Sidecar written by a previous init / doctor --fix
+ try {
+ const sidecar = path.join(targetDir, MEMORY_SIDECAR_REL);
+ if (fs.existsSync(sidecar)) {
+ const rec = JSON.parse(fs.readFileSync(sidecar, 'utf-8')) as Partial<MemoryPackageRecord>;
+ if (rec?.distPath && fs.existsSync(rec.distPath)) return rec.distPath;
+ }
+ } catch {
+ /* fall through */
+ }
+
+ // 2. createRequire from the project's package.json (direct/transitive dep)
+ try {
+ const require = createRequire(path.join(targetDir, 'package.json'));
+ return require.resolve(MEMORY_PACKAGE);
+ } catch {
+ /* fall through */
+ }
+
+ // 3. node_modules walk-up from the project root
+ let dir = path.resolve(targetDir);
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ const candidate = path.join(dir, 'node_modules', '@claude-flow', 'memory', 'dist', 'index.js');
+ if (fs.existsSync(candidate)) return candidate;
+ const parent = path.dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+
+ return null;
+}
+
+/** Read the version of the resolved memory package (dist/index.js β†’ ../package.json). */
+export function readMemoryPackageVersion(distPath: string): string | null {
+ try {
+ const pkgJson = path.resolve(path.dirname(distPath), '..', 'package.json');
+ if (fs.existsSync(pkgJson)) {
+ const parsed = JSON.parse(fs.readFileSync(pkgJson, 'utf-8')) as { version?: string };
+ return parsed.version ?? null;
+ }
+ } catch {
+ /* ignore */
+ }
+ return null;
+}
+
+/**
+ * Best-effort: resolve `@claude-flow/memory` from the CLI and record its path in
+ * the project sidecar so the runtime hook can find it on the npx install path.
+ * Returns the written record, or null when the package is not resolvable from the
+ * CLI (in which case the hook fails loud and `doctor` flags it).
+ */
+export function recordMemoryPackagePath(
+ targetDir: string,
+ resolvedBy = 'init',
+): MemoryPackageRecord | null {
+ const distPath = resolveMemoryPackageFromCli();
+ if (!distPath) return null;
+
+ const record: MemoryPackageRecord = {
+ distPath,
+ version: readMemoryPackageVersion(distPath),
+ resolvedBy,
+ resolvedAt: new Date().toISOString(),
+ };
+
+ try {
+ fs.mkdirSync(path.join(targetDir, '.claude-flow'), { recursive: true });
+ fs.writeFileSync(
+ path.join(targetDir, MEMORY_SIDECAR_REL),
+ JSON.stringify(record, null, 2),
+ 'utf-8',
+ );
+ return record;
+ } catch {
+ return null;
+ }
+}