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): refresh session companions during upgrade

xiajiahang89d73bcba518
diff --git a/.claude/helpers/intelligence.cjs b/.claude/helpers/intelligence.cjs
index f87c685044..ec7380d24c 100755
--- a/.claude/helpers/intelligence.cjs
+++ b/.claude/helpers/intelligence.cjs
@@ -277,11 +277,9 @@ function sessionGet(key) {
function sessionSet(key, value) {
try {
- if (!fs.existsSync(SESSION_DIR)) fs.mkdirSync(SESSION_DIR, { recursive: true });
- let session = {};
- if (fs.existsSync(SESSION_FILE)) {
- session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
- }
+ // Session creation belongs to session.cjs; recall may run before SessionStart.
+ if (!fs.existsSync(SESSION_FILE)) return;
+ const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
if (!session.context) session.context = {};
session.context[key] = value;
session.updatedAt = new Date().toISOString();
diff --git a/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs b/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs
index f87c685044..ec7380d24c 100755
--- a/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs
+++ b/v3/@claude-flow/cli/.claude/helpers/intelligence.cjs
@@ -277,11 +277,9 @@ function sessionGet(key) {
function sessionSet(key, value) {
try {
- if (!fs.existsSync(SESSION_DIR)) fs.mkdirSync(SESSION_DIR, { recursive: true });
- let session = {};
- if (fs.existsSync(SESSION_FILE)) {
- session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
- }
+ // Session creation belongs to session.cjs; recall may run before SessionStart.
+ if (!fs.existsSync(SESSION_FILE)) return;
+ const session = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8'));
if (!session.context) session.context = {};
session.context[key] = value;
session.updatedAt = new Date().toISOString();
diff --git a/v3/@claude-flow/cli/__tests__/session-upgrade-4198.test.ts b/v3/@claude-flow/cli/__tests__/session-upgrade-4198.test.ts
new file mode 100644
index 0000000000..192240a3cc
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/session-upgrade-4198.test.ts
@@ -0,0 +1,118 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { spawnSync } from 'node:child_process';
+import { executeUpgrade } from '../src/init/executor.js';
+import { generateIntelligenceStub } from '../src/init/helpers-generator.js';
+import { ensureCommonJsCompanions } from '../src/init/helper-companions.js';
+
+const roots: string[] = [];
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
+
+function project() {
+ const cwd = mkdtempSync(join(tmpdir(), 'ruflo-4198-'));
+ roots.push(cwd);
+ mkdirSync(join(cwd, '.claude', 'helpers'), { recursive: true });
+ mkdirSync(join(cwd, '.claude-flow', 'sessions'), { recursive: true });
+ writeFileSync(join(cwd, 'package.json'), '{"type":"module"}');
+ return cwd;
+}
+
+function run(cwd: string, script: string) {
+ const result = spawnSync(process.execPath, ['-e', script], {
+ cwd, encoding: 'utf-8', timeout: 10_000,
+ env: { ...process.env, CLAUDE_PROJECT_DIR: cwd },
+ });
+ expect(result.stderr).toBe('');
+ expect(result.status).toBe(0);
+ return result.stdout;
+}
+
+describe('#4198 session helper upgrades', () => {
+ it('replaces stale companions while preserving existing session and memory data', async () => {
+ const cwd = project();
+ const helpers = join(cwd, '.claude', 'helpers');
+ for (const name of ['session.cjs', 'memory.cjs']) writeFileSync(join(helpers, name), '// stale');
+ const current = join(cwd, '.claude-flow', 'sessions', 'current.json');
+ const session = '{"id":"session-123","context":{"keep":"value"}}';
+ writeFileSync(current, session);
+ mkdirSync(join(cwd, '.claude-flow', 'data'), { recursive: true });
+ const memory = join(cwd, '.claude-flow', 'data', 'memory.json');
+ writeFileSync(memory, '{"keep":"memory"}');
+
+ const result = await executeUpgrade(cwd);
+ expect(result.success).toBe(true);
+ for (const name of ['session.cjs', 'memory.cjs']) {
+ expect(result.updated).toContain(`.claude/helpers/${name}`);
+ expect(readFileSync(join(helpers, name), 'utf-8')).not.toBe('// stale');
+ }
+ expect(readFileSync(current, 'utf-8')).toBe(session);
+ expect(readFileSync(memory, 'utf-8')).toBe('{"keep":"memory"}');
+ expect(run(cwd, "console.log(require('./.claude/helpers/session.cjs').restore().id)")).toContain('session-123');
+ run(cwd, "require('./.claude/helpers/session.cjs').end()");
+ expect(existsSync(join(cwd, '.claude-flow', 'sessions', 'session-123.json'))).toBe(true);
+ run(cwd, "require('./.claude/helpers/memory.cjs').set('test', 'value')");
+ expect(run(cwd, "console.log(require('./.claude/helpers/memory.cjs').get('test'))")).toContain('value');
+ expect(JSON.parse(readFileSync(memory, 'utf-8')).keep).toBe('memory');
+ });
+
+ it('reports missing companions as created', async () => {
+ const cwd = project();
+ const result = await executeUpgrade(cwd);
+ expect(result.success).toBe(true);
+ for (const name of ['session.cjs', 'memory.cjs']) {
+ expect(result.created).toContain(`.claude/helpers/${name}`);
+ expect(result.updated).not.toContain(`.claude/helpers/${name}`);
+ }
+ });
+
+ it('keeps existing companions during the default startup ensure', async () => {
+ const cwd = project();
+ const helpers = join(cwd, '.claude', 'helpers');
+ for (const name of ['session.cjs', 'memory.cjs', 'session.js', 'memory.js']) {
+ writeFileSync(join(helpers, name), '// custom helper');
+ }
+ expect(await ensureCommonJsCompanions(helpers)).toEqual([]);
+ for (const name of ['session.cjs', 'memory.cjs', 'session.js', 'memory.js']) {
+ expect(readFileSync(join(helpers, name), 'utf-8')).toBe('// custom helper');
+ }
+ });
+});
+
+const shipped = [
+ fileURLToPath(new URL('../.claude/helpers/intelligence.cjs', import.meta.url)),
+ fileURLToPath(new URL('../../../../.claude/helpers/intelligence.cjs', import.meta.url)),
+];
+
+describe.each([...shipped, 'generated'])('#4198 intelligence session ownership: %s', (source) => {
+ function recall(cwd: string) {
+ const helper = join(cwd, '.claude', 'helpers', 'intelligence.cjs');
+ writeFileSync(helper, source === 'generated' ? generateIntelligenceStub() : readFileSync(source, 'utf-8'));
+ const data = join(cwd, '.claude-flow', 'data');
+ mkdirSync(data, { recursive: true });
+ writeFileSync(join(data, 'ranked-context.json'), JSON.stringify({ entries: [{
+ id: 'pattern-1', content: 'database migration', summary: 'database migration',
+ words: ['database', 'migration'], category: 'patterns', confidence: 0.9, pageRank: 1,
+ }] }));
+ expect(run(cwd, "console.log(require('./.claude/helpers/intelligence.cjs').getContext('database migration'))"))
+ .toContain('database migration');
+ }
+
+ it('does not create a session during recall before SessionStart', () => {
+ const cwd = project();
+ recall(cwd);
+ expect(existsSync(join(cwd, '.claude-flow', 'sessions', 'current.json'))).toBe(false);
+ });
+
+ it('updates context without losing the active session identity or existing context', () => {
+ const cwd = project();
+ const current = join(cwd, '.claude-flow', 'sessions', 'current.json');
+ writeFileSync(current, JSON.stringify({ id: 'session-123', metrics: { edits: 2 }, context: { keep: 'value' } }));
+ recall(cwd);
+ expect(JSON.parse(readFileSync(current, 'utf-8'))).toMatchObject({
+ id: 'session-123', metrics: { edits: 2 }, context: { keep: 'value', lastMatchedPatterns: ['pattern-1'] },
+ });
+ });
+});
diff --git a/v3/@claude-flow/cli/src/init/executor.ts b/v3/@claude-flow/cli/src/init/executor.ts
index 1776a52002..9dd7785046 100644
--- a/v3/@claude-flow/cli/src/init/executor.ts
+++ b/v3/@claude-flow/cli/src/init/executor.ts
@@ -31,7 +31,7 @@ import {
import { getInstalledCliVersion, HELPERS_STAMP_FILE } from './helper-refresh.js';
import { generateClaudeMd } from './claudemd-generator.js';
import { recordMemoryPackagePath } from './memory-package-resolver.js';
-import { ensureCommonJsCompanions } from './helper-companions.js';
+import { COMMONJS_COMPANION_HELPERS, ensureCommonJsCompanions } from './helper-companions.js';
import { scanSettingsForRisk, formatRiskFindingsAsWarnings } from './settings-risk-scanner.js';
import { AUTO_MEMORY_HOOK_TIMEOUT_S, helperHookCommand, helperScopeFor, helperStatusLineCommand, pinToUserHelpers } from './helper-commands.js';
@@ -617,10 +617,16 @@ export async function executeUpgrade(targetDir: string, upgradeSettings = false)
}
}
- // #3555: the refreshed hook-handler requires the .cjs companions; older
- // installs only have session.js / memory.js, which can't load in ESM.
- for (const name of await ensureCommonJsCompanions(path.join(targetDir, '.claude', 'helpers'))) {
- result.created.push(`.claude/helpers/${name}`);
+ // #4198: refresh existing companions too, so upgraded hook handlers never
+ // keep obsolete session/memory logic. Generate from the CLI trust root.
+ const helpersDir = path.join(targetDir, '.claude', 'helpers');
+ const existingCompanions = new Set<string>(COMMONJS_COMPANION_HELPERS.filter(
+ (name) => fs.existsSync(path.join(helpersDir, name)),
+ ));
+ for (const name of await ensureCommonJsCompanions(helpersDir, true)) {
+ const changes = existingCompanions.has(name)
+ ? result.updated : result.created;
+ changes.push(`.claude/helpers/${name}`);
}
// Stamp the installed version so the startup auto-refresh treats these as
diff --git a/v3/@claude-flow/cli/src/init/helper-companions.ts b/v3/@claude-flow/cli/src/init/helper-companions.ts
index 286ac36dd4..9794a76c2c 100644
--- a/v3/@claude-flow/cli/src/init/helper-companions.ts
+++ b/v3/@claude-flow/cli/src/init/helper-companions.ts
@@ -7,15 +7,16 @@
* `.js` copies, which the refreshed hook-handler no longer requires, so the
* refresh writes any missing `.cjs` companion from the CLI's own compiled
* generators (the trust root; no external file to verify). Stale `.js` copies
- * are left in place and ignored. Existing `.cjs` files are never overwritten.
+ * are left in place and ignored. Existing `.cjs` files are preserved during
+ * startup refresh; an explicit init upgrade replaces them from the generators.
*/
import * as fs from 'fs';
import * as path from 'path';
export const COMMONJS_COMPANION_HELPERS = ['session.cjs', 'memory.cjs'] as const;
-export async function ensureCommonJsCompanions(helpersDir: string): Promise<string[]> {
- const missing = COMMONJS_COMPANION_HELPERS.filter((name) => !fs.existsSync(path.join(helpersDir, name)));
+export async function ensureCommonJsCompanions(helpersDir: string, force = false): Promise<string[]> {
+ const missing = COMMONJS_COMPANION_HELPERS.filter((name) => force || !fs.existsSync(path.join(helpersDir, name)));
if (missing.length === 0) return [];
const gen = await import('./helpers-generator.js');
const content: Record<(typeof COMMONJS_COMPANION_HELPERS)[number], () => string> = {