🌊 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(hooks): expire command history and preserve failed outcomes
Rudy Celekli1738a045e2aa
diff --git a/v3/@claude-flow/cli/__tests__/command-history-retention-3447.test.ts b/v3/@claude-flow/cli/__tests__/command-history-retention-3447.test.tsnew file mode 100644index 0000000000..7fa16af6df--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/command-history-retention-3447.test.ts@@ -0,0 +1,76 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const mocks = vi.hoisted(() => ({ store: vi.fn(), call: vi.fn() }));+vi.mock('../src/mcp-client.js', () => ({ callMCPTool: mocks.call, MCPClientError: class extends Error {} }));+vi.mock('../src/memory/memory-bridge.js', () => ({ bridgeStoreEntry: mocks.store }));+vi.mock('../src/memory/intelligence.js', () => ({+ getIntelligenceStats: () => ({ trajectoriesRecorded: 0 }),+ recordTrajectory: vi.fn(async () => {}),+}));+import { hooksPostCommand } from '../src/mcp-tools/hooks-tools.js';+import { hooksCommand } from '../src/commands/hooks.js';++let dir: string;+beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'ruflo-command-history-'));+ vi.stubEnv('CLAUDE_FLOW_CWD', dir);+ mocks.store.mockReset().mockResolvedValue({ success: true, id: 'stored' });+ mocks.call.mockReset();+});+afterEach(() => { vi.unstubAllEnvs(); rmSync(dir, { recursive: true, force: true }); });++describe('command history retention and outcomes (#3447)', () => {+ it('bounds raw telemetry lifetime and skips unused command embeddings', async () => {+ await hooksPostCommand.handler({ command: 'npm test' });+ expect(mocks.store).toHaveBeenCalledWith(expect.objectContaining({+ ttl: 30 * 24 * 60 * 60, generateEmbeddingFlag: false,+ }));+ });++ it('honors an explicit failure even when the CLI supplies its default exit code', async () => {+ const result: any = await hooksPostCommand.handler({ command: 'npm test', success: false, exitCode: 0, ttl: 60 });+ expect(result.success).toBe(false);+ expect(mocks.store).toHaveBeenCalledWith(expect.objectContaining({ tags: ['error'], ttl: 60 }));+ });++ it('refuses invalid retention values before writing history', async () => {+ const result: any = await hooksPostCommand.handler({ command: 'npm test', ttl: -1 });+ expect(result.success).toBe(false);+ expect(result.error).toMatch(/ttl/i);+ expect(mocks.store).not.toHaveBeenCalled();+ });++ it.each([null, { success: false, error: 'read-only' }])('uses expiring JSON history when the bridge declines a write (%s)', async (outcome) => {+ mocks.store.mockResolvedValue(outcome);+ const result: any = await hooksPostCommand.handler({ command: 'npm test', ttl: 60 });+ expect(result._storedIn).toBe('json-store');+ const entries = Object.values(JSON.parse(readFileSync(join(dir, '.claude-flow/memory/store.json'), 'utf8')).entries) as any[];+ expect(entries).toHaveLength(1);+ expect(Date.parse(entries[0].expiresAt)).toBeGreaterThan(Date.now());+ });++ it('reclaims expired command fallback rows without deleting other namespaces', async () => {+ mocks.store.mockResolvedValue(null);+ const memoryDir = join(dir, '.claude-flow/memory');+ mkdirSync(memoryDir, { recursive: true });+ writeFileSync(join(memoryDir, 'store.json'), JSON.stringify({ version: '3.0.0', entries: {+ old: { namespace: 'commands', expiresAt: '2000-01-01T00:00:00Z' },+ keep: { namespace: 'patterns', expiresAt: '2000-01-01T00:00:00Z' },+ } }));+ await hooksPostCommand.handler({ command: 'npm test' });+ const store = JSON.parse(readFileSync(join(memoryDir, 'store.json'), 'utf8'));+ expect(store.entries.old).toBeUndefined();+ expect(store.entries.keep).toBeDefined();+ });++ it('forwards CLI retention and returns nonzero when no backend records the outcome', async () => {+ mocks.call.mockResolvedValue({ recorded: false, success: false });+ const postCommand = hooksCommand.subcommands!.find(c => c.name === 'post-command')!;+ const result = await postCommand.action!({ args: [], flags: { command: 'npm test', ttl: 120, success: false, format: 'json' } } as any);+ expect(mocks.call).toHaveBeenCalledWith('hooks_post-command', expect.objectContaining({ ttl: 120, success: false }));+ expect(result).toMatchObject({ success: false, exitCode: 1 });+ });+});diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.tsindex a9585659f0..32e2cce2de 100644--- a/v3/@claude-flow/cli/src/commands/hooks.ts+++ b/v3/@claude-flow/cli/src/commands/hooks.ts@@ -667,6 +667,11 @@ const postCommandCommand: Command = {short: 'd',description: 'Execution duration in milliseconds',type: 'number'+ },+ {+ name: 'ttl',+ description: 'Command history lifetime in seconds (default: 30 days)',+ type: 'number'}],examples: [@@ -700,14 +705,19 @@ const postCommandCommand: Command = {success,exitCode: ctx.flags.exitCode || 0,duration: ctx.flags.duration,+ ttl: ctx.flags.ttl,timestamp: Date.now(),});if (ctx.flags.format === 'json') {output.printJson(result);- return { success: true, data: result };+ return { success: result.recorded, exitCode: result.recorded ? 0 : 1, data: result };}+ if (!result.recorded) {+ output.printError('Command outcome could not be recorded');+ return { success: false, exitCode: 1, data: result };+ }output.writeln();output.printSuccess('Command outcome recorded');diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.tsindex 32cf57dbc4..9619d7e4ce 100644--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts@@ -522,6 +522,7 @@ interface MemoryEntry {storedAt: string;accessCount: number;lastAccessed: string;+ expiresAt?: string;}interface MemoryStore {@@ -1079,13 +1080,19 @@ export const hooksPostCommand: MCPTool = {properties: {command: { type: 'string', description: 'Executed command' },exitCode: { type: 'number', description: 'Command exit code' },+ success: { type: 'boolean', description: 'Explicit execution outcome; false records a failure even without a nonzero exit code' },+ ttl: { type: 'integer', minimum: 1, maximum: 2147483647, description: 'Command history lifetime in seconds (default: 30 days)' },},required: ['command'],},handler: async (params: Record<string, unknown>) => {const command = params.command as string;const exitCode = (params.exitCode as number) || 0;- const success = exitCode === 0;+ const success = exitCode === 0 && params.success !== false;+ const ttl = params.ttl ?? 30 * 24 * 60 * 60;+ if (typeof ttl !== 'number' || !Number.isSafeInteger(ttl) || ttl < 1 || ttl > 2147483647) {+ return { success: false, recorded: false, error: 'ttl must be a positive integer number of seconds (at most 2147483647)' };+ }{ const v = validateText(command, 'command'); if (!v.valid) return { success: false, error: v.error }; }@@ -1097,20 +1104,33 @@ export const hooksPostCommand: MCPTool = {let _storedIn: 'agentdb' | 'json-store' | 'none' = 'none';try {const bridge = await import('../memory/memory-bridge.js');- await bridge.bridgeStoreEntry({+ const stored = await bridge.bridgeStoreEntry({key: `cmd-${Date.now()}`,value: JSON.stringify({ command, exitCode, success }),namespace: 'commands',tags: [success ? 'success' : 'error'],+ ttl,+ generateEmbeddingFlag: false,});+ if (!stored?.success) throw new Error(stored?.error || 'Native bridge did not store the command');_storedIn = 'agentdb';} catch {// AgentDB not available — store in JSONtry {const store = loadMemoryStore();- const key = `cmd-${Date.now()}`;- store.entries[key] = { key, value: JSON.stringify({ command, exitCode, success }), namespace: 'commands', createdAt: new Date().toISOString() } as any;- const memDir = resolve(MEMORY_DIR);+ const now = Date.now();+ for (const [entryKey, entry] of Object.entries(store.entries)) {+ if (entry.namespace === 'commands' && entry.expiresAt && Date.parse(entry.expiresAt) <= now) {+ delete store.entries[entryKey];+ }+ }+ const key = `cmd-${now}`;+ store.entries[key] = {+ key, value: JSON.stringify({ command, exitCode, success }), namespace: 'commands',+ storedAt: new Date(now).toISOString(), lastAccessed: new Date(now).toISOString(), accessCount: 0,+ expiresAt: new Date(now + ttl * 1000).toISOString(),+ };+ const memDir = dirname(getMemoryPath());if (!existsSync(memDir)) mkdirSync(memDir, { recursive: true });writeFileSync(getMemoryPath(), JSON.stringify(store, null, 2), 'utf-8');_storedIn = 'json-store';