π 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
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(helpers): resolve modules from the helper root and keep session writes in the project
Dragan Spiridonov4cc18753f9e2
diff --git a/.claude/helpers/auto-memory-hook.mjs b/.claude/helpers/auto-memory-hook.mjsindex a83ce6cece..58ea812470 100755--- a/.claude/helpers/auto-memory-hook.mjs+++ b/.claude/helpers/auto-memory-hook.mjs@@ -17,11 +17,16 @@ import { fileURLToPath } from 'url';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);+// Executable modules resolve only from the helper's own install root. A+// home-level helper can serve an untrusted project, so CLAUDE_PROJECT_DIR must+// never decide which JavaScript gets imported.+const MODULE_ROOT = join(__dirname, '../..');// Home-level helpers can serve a different project. Keep the memory writer on// the same project root as intelligence.cjs, which reads CLAUDE_PROJECT_DIR.+// PROJECT_ROOT is for data only.const PROJECT_ROOT = process.env.CLAUDE_PROJECT_DIR? resolve(process.env.CLAUDE_PROJECT_DIR)- : join(__dirname, '../..');+ : MODULE_ROOT;const DATA_DIR = join(PROJECT_ROOT, '.claude-flow', 'data');const STORE_PATH = join(DATA_DIR, 'auto-memory-store.json');@@ -41,7 +46,7 @@ const dim = (msg) => console.log(` ${DIM}${msg}${RESET}`);// 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 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}`);@@ -175,7 +180,7 @@ async function loadMemoryPackage() {// 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');+ 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)) {@@ -185,7 +190,7 @@ async function loadMemoryPackage() {} catch { /* fall through */ }// Strategy 1: Local dev (built dist)- const localDist = join(PROJECT_ROOT, 'v3/@claude-flow/memory/dist/index.js');+ const localDist = join(MODULE_ROOT, 'v3/@claude-flow/memory/dist/index.js');if (existsSync(localDist)) {try {return await import(`file://${localDist}`);@@ -196,7 +201,7 @@ async function loadMemoryPackage() {// when installed as a transitive dependency via npx ruflo / npx claude-flow)try {const { createRequire } = await import('module');- const require = createRequire(join(PROJECT_ROOT, 'package.json'));+ const require = createRequire(join(MODULE_ROOT, 'package.json'));return require('@claude-flow/memory');} catch { /* fall through */ }@@ -205,8 +210,8 @@ async function loadMemoryPackage() {return await import('@claude-flow/memory');} catch { /* fall through */ }- // Strategy 4: Walk up from PROJECT_ROOT looking for @claude-flow/memory in any node_modules- let searchDir = PROJECT_ROOT;+ // 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');@@ -378,7 +383,7 @@ async function doStatus() {const memPkg = await loadMemoryPackage();const config = readConfig();- const sidecar = join(PROJECT_ROOT, '.claude-flow', 'memory-package.json');+ const sidecar = join(MODULE_ROOT, '.claude-flow', 'memory-package.json');const hasSidecar = existsSync(sidecar);console.log('\n=== Auto Memory Bridge Status ===\n');diff --git a/.claude/helpers/learning-service.mjs b/.claude/helpers/learning-service.mjsindex 93fdc169f2..00fba977f5 100755--- a/.claude/helpers/learning-service.mjs+++ b/.claude/helpers/learning-service.mjs@@ -26,9 +26,12 @@ import Database from 'better-sqlite3';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);+// Executable modules resolve only from the helper's own install root; a+// home-level helper can serve an untrusted project. PROJECT_ROOT is data only.+const MODULE_ROOT = join(__dirname, '../..');const PROJECT_ROOT = process.env.CLAUDE_PROJECT_DIR? resolve(process.env.CLAUDE_PROJECT_DIR)- : join(__dirname, '../..');+ : MODULE_ROOT;const DATA_DIR = join(PROJECT_ROOT, '.claude-flow/learning');const DB_PATH = join(DATA_DIR, 'patterns.db');const METRICS_PATH = join(DATA_DIR, 'learning-metrics.json');@@ -463,7 +466,7 @@ class EmbeddingService {try {// Dynamically import agentic-flow OptimizedEmbedder- const agenticFlowPath = join(PROJECT_ROOT, 'node_modules/agentic-flow/dist/embeddings/optimized-embedder.js');+ const agenticFlowPath = join(MODULE_ROOT, 'node_modules/agentic-flow/dist/embeddings/optimized-embedder.js');if (existsSync(agenticFlowPath)) {const { getOptimizedEmbedder } = await import(agenticFlowPath);diff --git a/.claude/helpers/session.cjs b/.claude/helpers/session.cjsindex ffe53a9b2a..3647afada0 100644--- a/.claude/helpers/session.cjs+++ b/.claude/helpers/session.cjs@@ -6,6 +6,7 @@const fs = require('fs');const path = require('path');+const crypto = require('crypto');const os = require('os');const platform = os.platform();@@ -30,6 +31,40 @@ function getDataDir() {const SESSION_DIR = getDataDir();const SESSION_FILE = path.join(SESSION_DIR, 'current.json');+// Archive names are generated by start(); anything else in current.json is+// untrusted project content and must never pick a path.+const SESSION_ID = /^session-\d+$/;++// current.json lives in the opened project. A symlink there must never be read+// or written through, so only a regular file counts as an active session.+function hasSessionFile() {+ try { return fs.lstatSync(SESSION_FILE).isFile(); } catch { return false; }+}++function archiveId(id) {+ return SESSION_ID.test(String(id)) ? String(id) : `session-${Date.now()}`;+}++// The project session directory must resolve inside the project (no+// symlinked escape). The per-user fallback directory is not project-owned.+function assertSessionDirContained() {+ if (SESSION_DIR !== path.join(process.cwd(), '.claude-flow', 'sessions')) return;+ const root = fs.realpathSync(process.cwd());+ const rel = path.relative(root, fs.realpathSync(SESSION_DIR));+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {+ throw new Error('Session directory resolves outside the project');+ }+}++// Exclusive temp file + rename: never writes through a planted symlink, and+// rename() replaces a symlinked target instead of following it.+function atomicWrite(file, data) {+ assertSessionDirContained();+ const tmp = `${file}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`;+ fs.writeFileSync(tmp, data, { flag: 'wx' });+ fs.renameSync(tmp, file);+}+function ensureDir(dir) {if (!fs.existsSync(dir)) {fs.mkdirSync(dir, { recursive: true });@@ -48,25 +83,25 @@ const commands = {context: {},metrics: { edits: 0, commands: 0, tasks: 0, errors: 0 }};- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));+ atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));console.log(`Session started: ${sessionId}`);return session;},restore: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No session to restore');return null;}const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));session.restoredAt = new Date().toISOString();- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));+ atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));console.log(`Session restored: ${session.id}`);return session;},end: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No active session');return null;}@@ -74,17 +109,18 @@ const commands = {session.endedAt = new Date().toISOString();session.duration = Date.now() - new Date(session.startedAt).getTime();- const archivePath = path.join(SESSION_DIR, `${session.id}.json`);- fs.writeFileSync(archivePath, JSON.stringify(session, null, 2));+ // Archive under a validated name; a crafted id cannot pick the path.+ const id = archiveId(session.id);+ atomicWrite(path.join(SESSION_DIR, `${id}.json`), JSON.stringify(session, null, 2));fs.unlinkSync(SESSION_FILE);- console.log(`Session ended: ${session.id}`);+ console.log(`Session ended: ${id}`);console.log(`Duration: ${Math.round(session.duration / 1000 / 60)} minutes`);return session;},status: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No active session');return null;}@@ -98,13 +134,13 @@ const commands = {},metric: (name) => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {return null;}const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));if (session.metrics[name] !== undefined) {session.metrics[name]++;- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));+ atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));}return session;}diff --git a/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs b/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjsindex 1fbf9b00d0..85917f9167 100755--- a/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs+++ b/v3/@claude-flow/cli/.claude/helpers/auto-memory-hook.mjs@@ -17,11 +17,16 @@ import { fileURLToPath } from 'url';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);+// Executable modules resolve only from the helper's own install root. A+// home-level helper can serve an untrusted project, so CLAUDE_PROJECT_DIR must+// never decide which JavaScript gets imported.+const MODULE_ROOT = join(__dirname, '../..');// Home-level helpers can serve a different project. Keep the memory writer on// the same project root as intelligence.cjs, which reads CLAUDE_PROJECT_DIR.+// PROJECT_ROOT is for data only.const PROJECT_ROOT = process.env.CLAUDE_PROJECT_DIR? resolve(process.env.CLAUDE_PROJECT_DIR)- : join(__dirname, '../..');+ : MODULE_ROOT;const DATA_DIR = join(PROJECT_ROOT, '.claude-flow', 'data');const STORE_PATH = join(DATA_DIR, 'auto-memory-store.json');@@ -41,7 +46,7 @@ const dim = (msg) => console.log(` ${DIM}${msg}${RESET}`);// 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 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}`);@@ -175,7 +180,7 @@ async function loadMemoryPackage() {// 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');+ 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)) {@@ -185,7 +190,7 @@ async function loadMemoryPackage() {} catch { /* fall through */ }// Strategy 1: Local dev (built dist)- const localDist = join(PROJECT_ROOT, 'v3/@claude-flow/memory/dist/index.js');+ const localDist = join(MODULE_ROOT, 'v3/@claude-flow/memory/dist/index.js');if (existsSync(localDist)) {try {return await import(`file://${localDist}`);@@ -196,7 +201,7 @@ async function loadMemoryPackage() {// when installed as a transitive dependency via npx ruflo / npx @claude-flow/cli@latest)try {const { createRequire } = await import('module');- const require = createRequire(join(PROJECT_ROOT, 'package.json'));+ const require = createRequire(join(MODULE_ROOT, 'package.json'));return require('@claude-flow/memory');} catch { /* fall through */ }@@ -205,8 +210,8 @@ async function loadMemoryPackage() {return await import('@claude-flow/memory');} catch { /* fall through */ }- // Strategy 4: Walk up from PROJECT_ROOT looking for @claude-flow/memory in any node_modules- let searchDir = PROJECT_ROOT;+ // 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');@@ -378,7 +383,7 @@ async function doStatus() {const memPkg = await loadMemoryPackage();const config = readConfig();- const sidecar = join(PROJECT_ROOT, '.claude-flow', 'memory-package.json');+ const sidecar = join(MODULE_ROOT, '.claude-flow', 'memory-package.json');const hasSidecar = existsSync(sidecar);console.log('\n=== Auto Memory Bridge Status ===\n');diff --git a/v3/@claude-flow/cli/.claude/helpers/learning-service.mjs b/v3/@claude-flow/cli/.claude/helpers/learning-service.mjsindex bbe2fac8ab..ad68c0f7c7 100755--- a/v3/@claude-flow/cli/.claude/helpers/learning-service.mjs+++ b/v3/@claude-flow/cli/.claude/helpers/learning-service.mjs@@ -26,9 +26,12 @@ import Database from 'better-sqlite3';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);+// Executable modules resolve only from the helper's own install root; a+// home-level helper can serve an untrusted project. PROJECT_ROOT is data only.+const MODULE_ROOT = join(__dirname, '../..');const PROJECT_ROOT = process.env.CLAUDE_PROJECT_DIR? resolve(process.env.CLAUDE_PROJECT_DIR)- : join(__dirname, '../..');+ : MODULE_ROOT;const DATA_DIR = join(PROJECT_ROOT, '.claude-flow/learning');const DB_PATH = join(DATA_DIR, 'patterns.db');const METRICS_PATH = join(DATA_DIR, 'learning-metrics.json');@@ -463,7 +466,7 @@ class EmbeddingService {try {// Dynamically import agentic-flow OptimizedEmbedder- const agenticFlowPath = join(PROJECT_ROOT, 'node_modules/agentic-flow/dist/embeddings/optimized-embedder.js');+ const agenticFlowPath = join(MODULE_ROOT, 'node_modules/agentic-flow/dist/embeddings/optimized-embedder.js');if (existsSync(agenticFlowPath)) {const { getOptimizedEmbedder } = await import(agenticFlowPath);diff --git a/v3/@claude-flow/cli/.claude/helpers/session.cjs b/v3/@claude-flow/cli/.claude/helpers/session.cjsindex 2e42c8118b..3f91aa523e 100644--- a/v3/@claude-flow/cli/.claude/helpers/session.cjs+++ b/v3/@claude-flow/cli/.claude/helpers/session.cjs@@ -6,9 +6,32 @@const fs = require('fs');const path = require('path');+const crypto = require('crypto');const SESSION_DIR = path.join(process.cwd(), '.claude-flow', 'sessions');const SESSION_FILE = path.join(SESSION_DIR, 'current.json');+// Archive names are generated by start(); anything else in current.json is+// untrusted project content and must never pick a path.+const SESSION_ID = /^session-\d+$/;++// current.json lives in the opened project. A symlink there must never be read+// or written through, so only a regular file counts as an active session.+function hasSessionFile() {+ try { return fs.lstatSync(SESSION_FILE).isFile(); } catch { return false; }+}++function archiveId(id) {+ return SESSION_ID.test(String(id)) ? String(id) : `session-${Date.now()}`;+}++// The session directory must resolve inside the project (no symlinked escape).+function assertSessionDirContained() {+ const root = fs.realpathSync(process.cwd());+ const rel = path.relative(root, fs.realpathSync(SESSION_DIR));+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {+ throw new Error('Session directory resolves outside the project');+ }+}// #2307: Atomic write β serialize to a per-process temp file, then rename()// into place. rename() is atomic on the same filesystem, so concurrent writers@@ -18,9 +41,12 @@ const SESSION_FILE = path.join(SESSION_DIR, 'current.json');// tail dangling past the end (valid JSON + trailing garbage = parse error).// Temp name includes process.pid so concurrent writers don't collide on it.// Same class as #1707 (metrics) / #1637 (daemon-state) β session.js was missed.+// The temp file is created exclusively (never through a planted symlink) and+// rename() replaces a symlinked target instead of writing through it.function atomicWrite(file, data) {- const tmp = `${file}.tmp.${process.pid}`;- fs.writeFileSync(tmp, data);+ assertSessionDirContained();+ const tmp = `${file}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`;+ fs.writeFileSync(tmp, data, { flag: 'wx' });fs.renameSync(tmp, file);}@@ -48,7 +74,7 @@ const commands = {},restore: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No session to restore');return null;}@@ -70,7 +96,7 @@ const commands = {},end: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No active session');return null;}@@ -79,12 +105,12 @@ const commands = {session.endedAt = new Date().toISOString();session.duration = Date.now() - new Date(session.startedAt).getTime();- // Archive session- const archivePath = path.join(SESSION_DIR, `${session.id}.json`);- atomicWrite(archivePath, JSON.stringify(session, null, 2));+ // Archive session under a validated name; a crafted id cannot pick the path.+ const id = archiveId(session.id);+ atomicWrite(path.join(SESSION_DIR, `${id}.json`), JSON.stringify(session, null, 2));fs.unlinkSync(SESSION_FILE);- console.log(`Session ended: ${session.id}`);+ console.log(`Session ended: ${id}`);console.log(`Duration: ${Math.round(session.duration / 1000 / 60)} minutes`);console.log(`Metrics: ${JSON.stringify(session.metrics)}`);@@ -92,7 +118,7 @@ const commands = {},status: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No active session');return null;}@@ -109,7 +135,7 @@ const commands = {},update: (key, value) => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No active session');return null;}@@ -123,7 +149,7 @@ const commands = {},get: (key) => {- if (!fs.existsSync(SESSION_FILE)) return null;+ if (!hasSessionFile()) return null;try {const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));return key ? (session.context || {})[key] : session.context;@@ -131,7 +157,7 @@ const commands = {},metric: (name) => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {return null;}diff --git a/v3/@claude-flow/cli/__tests__/auto-memory-project-root-3286.test.ts b/v3/@claude-flow/cli/__tests__/auto-memory-project-root-3286.test.tsindex 8a8b6bda37..428ae55659 100644--- a/v3/@claude-flow/cli/__tests__/auto-memory-project-root-3286.test.ts+++ b/v3/@claude-flow/cli/__tests__/auto-memory-project-root-3286.test.ts@@ -46,7 +46,9 @@ describe('#3286 auto-memory project root', () => {for (const [name, source] of [['package', packageHook], ['repository', dogfoodHook]] as const) {it(`${name} helper imports and syncs into the project when invoked from HOME`, () => {const { project, home, hook } = fixture(source);- const mockMemory = join(project, 'mock-memory.mjs');+ // The memory package resolves from the helper's install root (HOME here),+ // never from the project; data still lands in the project.+ const mockMemory = join(home, 'mock-memory.mjs');writeFileSync(mockMemory, `import { writeFileSync } from 'node:fs';export class AutoMemoryBridge {@@ -62,14 +64,14 @@ export class AutoMemoryBridge {async curateIndex() {}}`);- mkdirSync(join(project, '.claude-flow'), { recursive: true });- writeFileSync(join(project, '.claude-flow', 'memory-package.json'), JSON.stringify({ distPath: mockMemory }));+ mkdirSync(join(home, '.claude-flow'), { recursive: true });+ writeFileSync(join(home, '.claude-flow', 'memory-package.json'), JSON.stringify({ distPath: mockMemory }));expect(run(hook, project, 'import')).toContain('Imported 1 entries');const store = join(project, '.claude-flow', 'data', 'auto-memory-store.json');expect(JSON.parse(readFileSync(store, 'utf8'))[0].content).toBe(project);expect(run(hook, project, 'sync')).toContain('Synced 1 entries');- expect(readFileSync(join(project, 'sync-root.txt'), 'utf8')).toBe(project);+ expect(readFileSync(join(home, 'sync-root.txt'), 'utf8')).toBe(project);expect(existsSync(join(home, '.claude-flow', 'data', 'auto-memory-store.json'))).toBe(false);});}diff --git a/v3/@claude-flow/cli/__tests__/helper-module-root-trust.test.ts b/v3/@claude-flow/cli/__tests__/helper-module-root-trust.test.tsnew file mode 100644index 0000000000..fbd9445617--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/helper-module-root-trust.test.ts@@ -0,0 +1,99 @@+/**+ * A home-level helper can serve an untrusted project: CLAUDE_PROJECT_DIR picks+ * where data goes, never which JavaScript is imported. Executable modules must+ * resolve from the helper's own install root.+ */+import { afterEach, describe, expect, it } from 'vitest';+import { spawnSync } from 'node:child_process';+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { generateAutoMemoryHook } from '../src/init/helpers-generator.js';++const here = dirname(fileURLToPath(import.meta.url));+const packageHelpers = resolve(here, '../.claude/helpers');+const dogfoodHelpers = resolve(here, '../../../../.claude/helpers');+const tempRoots: string[] = [];++afterEach(() => {+ for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true });+});++/** A module that leaves a marker file if it is ever imported. */+function payload(marker: string): string {+ return `import { writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(marker)}, 'executed');\n` ++ 'export class AutoMemoryBridge {}\n';+}++/** Plant a payload in every location the memory resolver has probed from the project. */+function plantProject(project: string, marker: string) {+ const write = (file: string, content: string) => {+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, content);+ };+ write(join(project, 'evil-sidecar.mjs'), payload(marker));+ write(join(project, '.claude-flow', 'memory-package.json'), JSON.stringify({ distPath: join(project, 'evil-sidecar.mjs') }));+ write(join(project, 'v3', '@claude-flow', 'memory', 'dist', 'index.js'), payload(marker));+ write(join(project, 'package.json'), JSON.stringify({ name: 'untrusted', type: 'module' }));+ const pkg = join(project, 'node_modules', '@claude-flow', 'memory');+ write(join(pkg, 'package.json'), JSON.stringify({ name: '@claude-flow/memory', type: 'module', main: 'dist/index.js' }));+ write(join(pkg, 'dist', 'index.js'), payload(marker));+}++function fixture(source: string | null) {+ const root = mkdtempSync(join(tmpdir(), 'ruflo-module-root-'));+ tempRoots.push(root);+ const project = join(root, 'project');+ const home = join(root, 'home');+ const hook = join(home, '.claude', 'helpers', 'auto-memory-hook.mjs');+ const marker = join(root, 'payload-executed');+ mkdirSync(dirname(hook), { recursive: true });+ if (source) copyFileSync(source, hook);+ else writeFileSync(hook, generateAutoMemoryHook());+ plantProject(project, marker);+ return { project, hook, marker };+}++function run(hook: string, project: string, command: string) {+ const result = spawnSync(process.execPath, [hook, command], {+ cwd: project,+ env: { ...process.env, CLAUDE_PROJECT_DIR: project },+ encoding: 'utf8',+ timeout: 10_000,+ });+ expect(result.error).toBeUndefined();+ return result;+}++describe('auto-memory-hook resolves modules from the helper root only', () => {+ const sources = [+ ['package', join(packageHelpers, 'auto-memory-hook.mjs')],+ ['repository', join(dogfoodHelpers, 'auto-memory-hook.mjs')],+ ['generated fallback', null],+ ] as const;++ for (const [name, source] of sources) {+ it(`${name} helper never imports project code from a home-level install`, () => {+ const { project, hook, marker } = fixture(source);+ for (const command of ['import', 'sync', 'status']) {+ run(hook, project, command);+ expect(existsSync(marker), `${command} executed a project module`).toBe(false);+ }+ });+ }+ // Project data placement for home-level helpers is covered by+ // auto-memory-project-root-3286.test.ts.+});++describe('learning-service resolves modules from the helper root only', () => {+ for (const [name, dir] of [['package', packageHelpers], ['repository', dogfoodHelpers]] as const) {+ it(`${name} helper builds import paths from MODULE_ROOT`, () => {+ const source = readFileSync(join(dir, 'learning-service.mjs'), 'utf8');+ expect(source).toContain("const MODULE_ROOT = join(__dirname, '../..');");+ expect(source).toMatch(/join\(MODULE_ROOT, 'node_modules\/agentic-flow\//);+ expect(source).not.toMatch(/join\(PROJECT_ROOT, 'node_modules/);+ });+ }+});diff --git a/v3/@claude-flow/cli/__tests__/session-helper-trust.test.ts b/v3/@claude-flow/cli/__tests__/session-helper-trust.test.tsnew file mode 100644index 0000000000..d8e8f8ad81--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/session-helper-trust.test.ts@@ -0,0 +1,123 @@+/**+ * session.cjs keeps its state in <project>/.claude-flow/sessions/current.json,+ * which the opened project controls. Its contents must never steer a write+ * outside that session directory.+ */+import { afterEach, describe, expect, it } from 'vitest';+import { spawnSync } from 'node:child_process';+import {+ copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import { generateCrossPlatformSessionManager, generateSessionManager } from '../src/init/helpers-generator.js';++const here = dirname(fileURLToPath(import.meta.url));+const tempRoots: string[] = [];++afterEach(() => {+ for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true });+});++const sources: ReadonlyArray<readonly [string, () => string | null, string | null]> = [+ ['package', () => null, resolve(here, '../.claude/helpers/session.cjs')],+ ['repository', () => null, resolve(here, '../../../../.claude/helpers/session.cjs')],+ ['generated', generateSessionManager, null],+ ['generated cross-platform', generateCrossPlatformSessionManager, null],+];++function fixture(generate: () => string | null, source: string | null) {+ const root = mkdtempSync(join(tmpdir(), 'ruflo-session-trust-'));+ tempRoots.push(root);+ const project = join(root, 'project');+ const home = join(root, 'home');+ const outside = join(root, 'outside');+ const helper = join(root, 'helpers', 'session.cjs');+ const sessions = join(project, '.claude-flow', 'sessions');+ for (const dir of [project, home, outside, dirname(helper)]) mkdirSync(dir, { recursive: true });+ if (source) copyFileSync(source, helper);+ else writeFileSync(helper, generate() as string);+ return { root, project, home, outside, helper, sessions };+}++function run(f: ReturnType<typeof fixture>, ...args: string[]) {+ const result = spawnSync(process.execPath, [f.helper, ...args], {+ cwd: f.project,+ env: { ...process.env, HOME: f.home, USERPROFILE: f.home, APPDATA: f.home },+ encoding: 'utf8',+ timeout: 10_000,+ });+ expect(result.error).toBeUndefined();+ return result;+}++function writeCurrent(sessions: string, session: Record<string, unknown>) {+ mkdirSync(sessions, { recursive: true });+ writeFileSync(join(sessions, 'current.json'), JSON.stringify(session));+}++describe('session helper keeps writes inside the project session dir', () => {+ for (const [name, generate, source] of sources) {+ describe(name, () => {+ it('a crafted session id cannot choose the archive path', () => {+ const f = fixture(generate, source);+ const escape = join(f.outside, 'escaped');+ writeCurrent(f.sessions, {+ id: `../../../outside/escaped`,+ startedAt: new Date().toISOString(),+ metrics: { edits: 0 },+ });++ run(f, 'end');++ expect(existsSync(`${escape}.json`)).toBe(false);+ expect(readdirSync(f.outside)).toEqual([]);+ const archived = readdirSync(f.sessions);+ expect(archived).toHaveLength(1);+ expect(archived[0]).toMatch(/^session-\d+\.json$/);+ });++ it('never writes through a symlinked current.json', () => {+ const f = fixture(generate, source);+ const target = join(f.outside, 'target.json');+ const original = JSON.stringify({ id: 'session-1', startedAt: new Date().toISOString(), metrics: { edits: 0 } });+ writeFileSync(target, original);+ mkdirSync(f.sessions, { recursive: true });+ symlinkSync(target, join(f.sessions, 'current.json'));++ run(f, 'restore');+ run(f, 'end');++ expect(readFileSync(target, 'utf8')).toBe(original);+ expect(readdirSync(f.outside)).toEqual(['target.json']);+ });++ it('refuses a session directory that resolves outside the project', () => {+ const f = fixture(generate, source);+ mkdirSync(join(f.project, '.claude-flow'), { recursive: true });+ symlinkSync(f.outside, f.sessions, 'dir');++ run(f, 'start');++ expect(readdirSync(f.outside)).toEqual([]);+ });++ it('keeps the normal start / restore / end lifecycle working', () => {+ const f = fixture(generate, source);+ mkdirSync(join(f.project, '.claude-flow'), { recursive: true });++ expect(run(f, 'start').stdout).toMatch(/Session started: session-\d+/);+ expect(run(f, 'restore').stdout).toMatch(/Session restored: session-\d+/);+ const ended = run(f, 'end').stdout;+ const id = /Session ended: (session-\d+)/.exec(ended)?.[1];++ expect(id).toBeDefined();+ expect(existsSync(join(f.sessions, `${id}.json`))).toBe(true);+ expect(existsSync(join(f.sessions, 'current.json'))).toBe(false);+ expect(readdirSync(f.sessions).filter((n) => n.includes('.tmp'))).toEqual([]);+ });+ });+ }+});diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.tsindex e7e3846864..e7ee6972f4 100644--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts@@ -132,10 +132,43 @@ export function generateSessionManager(): string {const fs = require('fs');const path = require('path');+const crypto = require('crypto');const SESSION_DIR = path.join(process.cwd(), '.claude-flow', 'sessions');const SESSION_FILE = path.join(SESSION_DIR, 'current.json');+// Archive names are generated by start(); anything else in current.json is+// untrusted project content and must never pick a path.+const SESSION_ID = /^session-\\d+$/;++// current.json lives in the opened project. A symlink there must never be read+// or written through, so only a regular file counts as an active session.+function hasSessionFile() {+ try { return fs.lstatSync(SESSION_FILE).isFile(); } catch { return false; }+}++function archiveId(id) {+ return SESSION_ID.test(String(id)) ? String(id) : \`session-\${Date.now()}\`;+}++// The session directory must resolve inside the project (no symlinked escape).+function assertSessionDirContained() {+ const root = fs.realpathSync(process.cwd());+ const rel = path.relative(root, fs.realpathSync(SESSION_DIR));+ if (rel === '..' || rel.startsWith(\`..\${path.sep}\`) || path.isAbsolute(rel)) {+ throw new Error('Session directory resolves outside the project');+ }+}++// Exclusive temp file + rename: never writes through a planted symlink, and+// rename() replaces a symlinked target instead of following it.+function atomicWrite(file, data) {+ assertSessionDirContained();+ const tmp = \`\${file}.tmp.\${process.pid}.\${crypto.randomBytes(6).toString('hex')}\`;+ fs.writeFileSync(tmp, data, { flag: 'wx' });+ fs.renameSync(tmp, file);+}+const commands = {start: () => {const sessionId = \`session-\${Date.now()}\`;@@ -153,28 +186,28 @@ const commands = {};fs.mkdirSync(SESSION_DIR, { recursive: true });- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));+ atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));console.log(\`Session started: \${sessionId}\`);return session;},restore: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No session to restore');return null;}const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));session.restoredAt = new Date().toISOString();- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));+ atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));console.log(\`Session restored: \${session.id}\`);return session;},end: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No active session');return null;}@@ -183,12 +216,12 @@ const commands = {session.endedAt = new Date().toISOString();session.duration = Date.now() - new Date(session.startedAt).getTime();- // Archive session- const archivePath = path.join(SESSION_DIR, \`\${session.id}.json\`);- fs.writeFileSync(archivePath, JSON.stringify(session, null, 2));+ // Archive session under a validated name; a crafted id cannot pick the path.+ const id = archiveId(session.id);+ atomicWrite(path.join(SESSION_DIR, \`\${id}.json\`), JSON.stringify(session, null, 2));fs.unlinkSync(SESSION_FILE);- console.log(\`Session ended: \${session.id}\`);+ console.log(\`Session ended: \${id}\`);console.log(\`Duration: \${Math.round(session.duration / 1000 / 60)} minutes\`);console.log(\`Metrics: \${JSON.stringify(session.metrics)}\`);@@ -196,7 +229,7 @@ const commands = {},status: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No active session');return null;}@@ -213,7 +246,7 @@ const commands = {},update: (key, value) => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No active session');return null;}@@ -221,20 +254,20 @@ const commands = {const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));session.context[key] = value;session.updatedAt = new Date().toISOString();- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));+ atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));return session;},metric: (name) => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {return null;}const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));if (session.metrics[name] !== undefined) {session.metrics[name]++;- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));+ atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));}return session;@@ -1168,9 +1201,12 @@ import { fileURLToPath } from 'url';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);+// Executable modules resolve only from the helper's own install root; a+// home-level helper can serve an untrusted project. PROJECT_ROOT is data only.+const MODULE_ROOT = join(__dirname, '../..');const PROJECT_ROOT = process.env.CLAUDE_PROJECT_DIR? resolve(process.env.CLAUDE_PROJECT_DIR)- : join(__dirname, '../..');+ : MODULE_ROOT;const DATA_DIR = join(PROJECT_ROOT, '.claude-flow', 'data');const STORE_PATH = join(DATA_DIR, 'auto-memory-store.json');@@ -1182,7 +1218,7 @@ 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 l1 = \`[AutoMemory] @claude-flow/memory not resolvable from \${MODULE_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}\`);@@ -1197,7 +1233,7 @@ async function loadMemoryPackage() {// 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');+ const sidecar = join(MODULE_ROOT, '.claude-flow', 'memory-package.json');if (existsSync(sidecar)) {const rec = JSON.parse(readFileSync(sidecar, 'utf-8'));if (rec && rec.distPath && existsSync(rec.distPath)) {@@ -1210,15 +1246,15 @@ async function loadMemoryPackage() {// when installed as a transitive dependency via npx ruflo / npx claude-flow)try {const { createRequire } = await import('module');- const require = createRequire(join(PROJECT_ROOT, 'package.json'));+ const require = createRequire(join(MODULE_ROOT, 'package.json'));return require('@claude-flow/memory');} catch { /* fall through */ }// Strategy 2: ESM import (works when @claude-flow/memory is a direct dependency)try { return await import('@claude-flow/memory'); } catch { /* fall through */ }- // Strategy 3: Walk up from PROJECT_ROOT looking for the package in any node_modules- let searchDir = PROJECT_ROOT;+ // Strategy 3: Walk up from MODULE_ROOT looking for the package 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');@@ -1419,6 +1455,7 @@ export function generateCrossPlatformSessionManager(): string {const fs = require('fs');const path = require('path');+const crypto = require('crypto');const os = require('os');// Platform-specific paths@@ -1445,6 +1482,40 @@ function getDataDir() {const SESSION_DIR = getDataDir();const SESSION_FILE = path.join(SESSION_DIR, 'current.json');+// Archive names are generated by start(); anything else in current.json is+// untrusted project content and must never pick a path.+const SESSION_ID = /^session-\\d+$/;++// current.json lives in the opened project. A symlink there must never be read+// or written through, so only a regular file counts as an active session.+function hasSessionFile() {+ try { return fs.lstatSync(SESSION_FILE).isFile(); } catch { return false; }+}++function archiveId(id) {+ return SESSION_ID.test(String(id)) ? String(id) : \`session-\${Date.now()}\`;+}++// The project session directory must resolve inside the project (no+// symlinked escape). The per-user fallback directory is not project-owned.+function assertSessionDirContained() {+ if (SESSION_DIR !== path.join(process.cwd(), '.claude-flow', 'sessions')) return;+ const root = fs.realpathSync(process.cwd());+ const rel = path.relative(root, fs.realpathSync(SESSION_DIR));+ if (rel === '..' || rel.startsWith(\`..\${path.sep}\`) || path.isAbsolute(rel)) {+ throw new Error('Session directory resolves outside the project');+ }+}++// Exclusive temp file + rename: never writes through a planted symlink, and+// rename() replaces a symlinked target instead of following it.+function atomicWrite(file, data) {+ assertSessionDirContained();+ const tmp = \`\${file}.tmp.\${process.pid}.\${crypto.randomBytes(6).toString('hex')}\`;+ fs.writeFileSync(tmp, data, { flag: 'wx' });+ fs.renameSync(tmp, file);+}+// Ensure directory existsfunction ensureDir(dir) {if (!fs.existsSync(dir)) {@@ -1464,25 +1535,25 @@ const commands = {context: {},metrics: { edits: 0, commands: 0, tasks: 0, errors: 0 }};- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));+ atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));console.log(\`Session started: \${sessionId}\`);return session;},restore: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No session to restore');return null;}const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));session.restoredAt = new Date().toISOString();- fs.writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));+ atomicWrite(SESSION_FILE, JSON.stringify(session, null, 2));console.log(\`Session restored: \${session.id}\`);return session;},end: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No active session');return null;}@@ -1490,17 +1561,18 @@ const commands = {session.endedAt = new Date().toISOString();session.duration = Date.now() - new Date(session.startedAt).getTime();- const archivePath = path.join(SESSION_DIR, \`\${session.id}.json\`);- fs.writeFileSync(archivePath, JSON.stringify(session, null, 2));+ // Archive under a validated name; a crafted id cannot pick the path.+ const id = archiveId(session.id);+ atomicWrite(path.join(SESSION_DIR, \`\${id}.json\`), JSON.stringify(session, null, 2));fs.unlinkSync(SESSION_FILE);- console.log(\`Session ended: \${session.id}\`);+ console.log(\`Session ended: \${id}\`);console.log(\`Duration: \${Math.round(session.duration / 1000 / 60)} minutes\`);return session;},status: () => {- if (!fs.existsSync(SESSION_FILE)) {+ if (!hasSessionFile()) {console.log('No active session');return null;}