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

feat(intelligence): Hermes-Agent Tier-1 adoptions β€” prompt caching, reasoning scrub, tool-loop breaker (3.10.10) (#2237)

rUvc983c0d8092f
diff --git a/package-lock.json b/package-lock.json
index 3a67c2702e..03193e48f9 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "claude-flow",
- "version": "3.10.9",
+ "version": "3.10.10",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "claude-flow",
- "version": "3.10.9",
+ "version": "3.10.10",
"license": "MIT",
"dependencies": {
"@claude-flow/cli-core": "^3.7.0-alpha.5",
diff --git a/package.json b/package.json
index 710a8b76d2..fc1eabd9c2 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-flow",
- "version": "3.10.9",
+ "version": "3.10.10",
"description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "dist/index.js",
"type": "module",
diff --git a/ruflo/package.json b/ruflo/package.json
index f942cedcf7..9bebddf53e 100644
--- a/ruflo/package.json
+++ b/ruflo/package.json
@@ -1,6 +1,6 @@
{
"name": "ruflo",
- "version": "3.10.9",
+ "version": "3.10.10",
"description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
"main": "bin/ruflo.js",
"type": "module",
diff --git a/v3/@claude-flow/cli/__tests__/hermes-tier1.test.ts b/v3/@claude-flow/cli/__tests__/hermes-tier1.test.ts
new file mode 100644
index 0000000000..a1c7e1c41e
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/hermes-tier1.test.ts
@@ -0,0 +1,70 @@
+/**
+ * Hermes-Agent Tier-1 adoptions (see docs/reviews/intelligence-system-audit-2026-05-29.md
+ * β†’ Hermes capability map):
+ * #14 β€” reasoning-tag scrubbing keeps extended-thinking blocks out of the
+ * learning trajectory (so DISTILL doesn't embed reasoning tokens).
+ * #6 β€” tool-loop circuit breaker warns/blocks on repeated consecutive
+ * failures of the same command.
+ */
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import { scrubReasoningBlocks } from '../src/mcp-tools/hooks-tools.js';
+import {
+ checkCommandLoop,
+ recordCommandOutcome,
+ _resetLoopHistory,
+} from '../src/mcp-tools/tool-loop-guardrail.js';
+
+describe('#14 β€” reasoning-tag scrubbing', () => {
+ it('strips paired thinking/reasoning blocks', () => {
+ expect(scrubReasoningBlocks('did it <think>secret CoT</think> ok')).toBe('did it ok');
+ expect(scrubReasoningBlocks('a<thinking>x</thinking>b')).toBe('ab');
+ expect(scrubReasoningBlocks('a<reasoning>y</reasoning>b')).toBe('ab');
+ expect(scrubReasoningBlocks('a<REASONING_SCRATCHPAD>z</REASONING_SCRATCHPAD>b')).toBe('ab');
+ });
+ it('leaves prose that merely mentions the tag untouched (boundary-gated)', () => {
+ expect(scrubReasoningBlocks('We document the <think> tag here')).toBe('We document the <think> tag here');
+ });
+ it('is a no-op on tag-free text and non-strings', () => {
+ expect(scrubReasoningBlocks('plain output')).toBe('plain output');
+ expect(scrubReasoningBlocks(undefined as unknown as string)).toBe(undefined);
+ });
+});
+
+describe('#6 β€” tool-loop circuit breaker', () => {
+ beforeEach(() => _resetLoopHistory());
+
+ it('allows until the warn threshold, then warns, then blocks', () => {
+ const cmd = 'npm run flaky';
+ expect(checkCommandLoop(cmd).verdict).toBe('allow');
+ recordCommandOutcome(cmd, false);
+ recordCommandOutcome(cmd, false);
+ expect(checkCommandLoop(cmd).verdict).toBe('allow'); // 2 fails
+ recordCommandOutcome(cmd, false);
+ expect(checkCommandLoop(cmd).verdict).toBe('warn'); // 3 fails
+ recordCommandOutcome(cmd, false);
+ recordCommandOutcome(cmd, false);
+ const v = checkCommandLoop(cmd);
+ expect(v.verdict).toBe('block'); // 5 fails
+ expect(v.consecutiveFailures).toBe(5);
+ expect(v.hint).toMatch(/failed 5/);
+ });
+
+ it('a success resets the streak', () => {
+ const cmd = 'pytest';
+ for (let i = 0; i < 5; i++) recordCommandOutcome(cmd, false);
+ expect(checkCommandLoop(cmd).verdict).toBe('block');
+ recordCommandOutcome(cmd, true);
+ expect(checkCommandLoop(cmd).verdict).toBe('allow');
+ });
+
+ it('interleaved other commands do not break the streak (exact-match only)', () => {
+ recordCommandOutcome('build', false);
+ recordCommandOutcome('ls', true); // different command
+ recordCommandOutcome('build', false);
+ recordCommandOutcome('git status', true);
+ recordCommandOutcome('build', false);
+ expect(checkCommandLoop('build').verdict).toBe('warn'); // 3 build failures, ls/git ignored
+ expect(checkCommandLoop('ls').verdict).toBe('allow');
+ });
+});
diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json
index 44743f2f1e..0f09c647b9 100644
--- a/v3/@claude-flow/cli/package.json
+++ b/v3/@claude-flow/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/cli",
- "version": "3.10.9",
+ "version": "3.10.10",
"type": "module",
"description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code",
"main": "dist/src/index.js",
diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
index da3af4f534..1ef57d6e3d 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/agent-execute-core.ts
@@ -150,7 +150,13 @@ export async function callAnthropicMessages(input: AnthropicCallInput): Promise<
model,
max_tokens: input.maxTokens || 1024,
temperature: typeof input.temperature === 'number' ? input.temperature : 0.7,
- ...(input.systemPrompt ? { system: input.systemPrompt } : {}),
+ // #8 prompt caching (hermes-agent pattern): mark the (often large,
+ // stable) system prompt as an ephemeral cache breakpoint so repeated
+ // agent_execute calls with the same system prompt hit Anthropic's
+ // prompt cache (~90% discount on cached input tokens, 5-min TTL).
+ ...(input.systemPrompt
+ ? { system: [{ type: 'text', text: input.systemPrompt, cache_control: { type: 'ephemeral' } }] }
+ : {}),
messages: [{ role: 'user', content: input.prompt }],
}),
signal: controller.signal,
diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
index feea4716be..7db8ca53bf 100644
--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts
@@ -7,6 +7,7 @@ import { mkdirSync, writeFileSync, existsSync, readFileSync, statSync, unlinkSyn
import { dirname, join, resolve } from 'path';
import { type MCPTool, getProjectCwd } from './types.js';
import { validateIdentifier, validateText, validatePath } from './validate-input.js';
+import { checkCommandLoop, recordCommandOutcome } from './tool-loop-guardrail.js';
// Real vector search functions - lazy loaded to avoid circular imports
let searchEntriesFn: ((options: {
@@ -21,6 +22,26 @@ let searchEntriesFn: ((options: {
error?: string;
}>) | null = null;
+/**
+ * Strip extended-thinking blocks from text before it enters a learning
+ * trajectory (hermes-agent think_scrubber pattern). Claude models with extended
+ * thinking emit <thinking>/<think>/<reasoning> blocks; if those land in a
+ * trajectory's action/result text, the DISTILL step embeds reasoning-token
+ * content that does not generalize, contaminating pattern confidence. Boundary-
+ * gated: only strips well-formed paired tags, leaving prose that merely mentions
+ * the tag names untouched.
+ */
+export function scrubReasoningBlocks(text: string): string {
+ if (typeof text !== 'string' || text.indexOf('<') === -1) return text;
+ return text
+ .replace(/<think>[\s\S]*?<\/think>/gi, '')
+ .replace(/<thinking>[\s\S]*?<\/thinking>/gi, '')
+ .replace(/<reasoning>[\s\S]*?<\/reasoning>/gi, '')
+ .replace(/<thought>[\s\S]*?<\/thought>/gi, '')
+ .replace(/<REASONING_SCRATCHPAD>[\s\S]*?<\/REASONING_SCRATCHPAD>/gi, '')
+ .trim();
+}
+
async function getRealSearchFunction() {
if (!searchEntriesFn) {
try {
@@ -812,6 +833,14 @@ export const hooksPreCommand: MCPTool = {
: assessment.level >= 0.3 ? 'medium'
: 'low';
+ // #6: tool-loop circuit breaker β€” warn/block when this exact command has
+ // failed repeatedly in a row (an agent stuck looping on a failing call).
+ const loop = checkCommandLoop(command);
+ const recommendations = assessment.warnings.length > 0
+ ? ['Review warnings before proceeding', 'Consider using safer alternative']
+ : ['Command appears safe to execute'];
+ if (loop.hint) recommendations.unshift(loop.hint);
+
return {
command,
riskLevel,
@@ -820,11 +849,11 @@ export const hooksPreCommand: MCPTool = {
severity: assessment.level >= 0.6 ? 'high' : 'medium',
description: warning,
})),
- recommendations: assessment.warnings.length > 0
- ? ['Review warnings before proceeding', 'Consider using safer alternative']
- : ['Command appears safe to execute'],
+ recommendations,
+ loopGuard: { verdict: loop.verdict, consecutiveFailures: loop.consecutiveFailures },
safeAlternatives: [],
- shouldProceed: assessment.level < 0.7,
+ // Don't proceed on a high-risk command OR a hard loop-block.
+ shouldProceed: assessment.level < 0.7 && loop.verdict !== 'block',
};
},
};
@@ -847,6 +876,10 @@ export const hooksPostCommand: MCPTool = {
{ const v = validateText(command, 'command'); if (!v.valid) return { success: false, error: v.error }; }
+ // #6: feed the tool-loop circuit breaker so pre-command can warn/block on
+ // repeated consecutive failures of the same command.
+ recordCommandOutcome(command, success);
+
// Persist command outcome via AgentDB
let _storedIn: 'agentdb' | 'json-store' | 'none' = 'none';
try {
@@ -2443,8 +2476,10 @@ export const hooksTrajectoryStep: MCPTool = {
},
handler: async (params: Record<string, unknown>) => {
const trajectoryId = params.trajectoryId as string;
- const action = params.action as string;
- const result = (params.result as string) || 'success';
+ // #14: scrub extended-thinking blocks so reasoning tokens don't contaminate
+ // the learning signal (DISTILL embeds this text).
+ const action = scrubReasoningBlocks(params.action as string);
+ const result = scrubReasoningBlocks((params.result as string) || 'success');
const quality = (params.quality as number) || 0.85;
const timestamp = new Date().toISOString();
const stepId = `step-${Date.now()}`;
diff --git a/v3/@claude-flow/cli/src/mcp-tools/tool-loop-guardrail.ts b/v3/@claude-flow/cli/src/mcp-tools/tool-loop-guardrail.ts
new file mode 100644
index 0000000000..e88c2a2010
--- /dev/null
+++ b/v3/@claude-flow/cli/src/mcp-tools/tool-loop-guardrail.ts
@@ -0,0 +1,82 @@
+/**
+ * Tool-loop circuit breaker (hermes-agent tool_guardrails pattern).
+ *
+ * Detects an agent stuck repeating the same failing command β€” a real silent
+ * failure mode where a loop burns turns with no signal. This is ORTHOGONAL to
+ * the security `tool-output-guardrail` (which detects indirect prompt injection
+ * in tool *output*); this one watches the agent's own *call* pattern.
+ *
+ * Design (deterministic, in-memory, bounded):
+ * - `recordCommandOutcome` (called by post-command) appends (command, success)
+ * to a small ring buffer.
+ * - `checkCommandLoop` (called by pre-command) returns a verdict for a command
+ * about to run, based on its recent consecutive-failure streak.
+ * - Verdict is advisory by default (`warn`); callers decide whether to block.
+ * An orchestration layer that doesn't own the UI should not hard-stop.
+ */
+
+export type LoopVerdict = 'allow' | 'warn' | 'block';
+
+interface Outcome { command: string; success: boolean; at: number }
+
+const MAX_HISTORY = 64;
+const history: Outcome[] = [];
+
+/** Consecutive-failure thresholds for the same command (exact match). */
+const WARN_AT = 3;
+const BLOCK_AT = 5;
+
+function normalize(command: string): string {
+ return command.trim().replace(/\s+/g, ' ');
+}
+
+/** Record a command's outcome. Called from the post-command hook. */
+export function recordCommandOutcome(command: string, success: boolean): void {
+ history.push({ command: normalize(command), success, at: history.length });
+ if (history.length > MAX_HISTORY) history.shift();
+}
+
+/** Count the trailing run of consecutive failures of `command` (exact match),
+ * stopping at the first success of that command or a gap. */
+function consecutiveFailures(command: string): number {
+ const norm = normalize(command);
+ let streak = 0;
+ for (let i = history.length - 1; i >= 0; i--) {
+ if (history[i].command !== norm) continue; // ignore interleaved other commands
+ if (history[i].success) break; // a success breaks the streak
+ streak++;
+ }
+ return streak;
+}
+
+/**
+ * Verdict for a command about to execute. Called from the pre-command hook.
+ * Returns the verdict, the failure streak, and a recovery hint when looping.
+ */
+export function checkCommandLoop(command: string): {
+ verdict: LoopVerdict;
+ consecutiveFailures: number;
+ hint?: string;
+} {
+ const fails = consecutiveFailures(command);
+ if (fails >= BLOCK_AT) {
+ return {
+ verdict: 'block',
+ consecutiveFailures: fails,
+ hint: `This exact command has failed ${fails}Γ— in a row. Stop repeating it β€” inspect state first (e.g. \`pwd && ls -la\`), change the approach, or ask for help.`,
+ };
+ }
+ if (fails >= WARN_AT) {
+ return {
+ verdict: 'warn',
+ consecutiveFailures: fails,
+ hint: `This command has failed ${fails}Γ— in a row. Before retrying, verify preconditions (paths, args, prior step output) rather than re-running the same call.`,
+ };
+ }
+ return { verdict: 'allow', consecutiveFailures: fails };
+}
+
+/** Test/reset helper β€” clears the in-memory history. */
+export function _resetLoopHistory(): void {
+ history.length = 0;
+}
diff --git a/v3/@claude-flow/providers/src/anthropic-provider.ts b/v3/@claude-flow/providers/src/anthropic-provider.ts
index e934d19d2b..7f5e0709c4 100644
--- a/v3/@claude-flow/providers/src/anthropic-provider.ts
+++ b/v3/@claude-flow/providers/src/anthropic-provider.ts
@@ -21,13 +21,14 @@ import {
LLMProviderError,
} from './types.js';
+interface CacheControl { type: 'ephemeral' }
interface AnthropicRequest {
model: string;
messages: Array<{
role: 'user' | 'assistant';
- content: string | Array<{ type: string; text?: string; source?: unknown }>;
+ content: string | Array<{ type: string; text?: string; source?: unknown; cache_control?: CacheControl }>;
}>;
- system?: string;
+ system?: string | Array<{ type: 'text'; text: string; cache_control?: CacheControl }>;
max_tokens: number;
temperature?: number;
top_p?: number;
@@ -310,7 +311,7 @@ export class AnthropicProvider extends BaseProvider {
const otherMessages = request.messages.filter((m) => m.role !== 'system');
// Transform messages
- const messages = otherMessages.map((msg) => ({
+ const messages: AnthropicRequest['messages'] = otherMessages.map((msg) => ({
role: msg.role as 'user' | 'assistant',
content: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),
}));
@@ -323,9 +324,32 @@ export class AnthropicProvider extends BaseProvider {
};
if (systemMessage) {
- anthropicRequest.system = typeof systemMessage.content === 'string'
+ const systemText = typeof systemMessage.content === 'string'
? systemMessage.content
: JSON.stringify(systemMessage.content);
+ // Prompt caching (hermes-agent pattern): mark the stable system prompt as
+ // an ephemeral cache breakpoint so multi-turn / repeated-system-prompt
+ // calls hit Anthropic's prompt cache (~90% discount on cached input
+ // tokens, 5-min TTL). Opt-out via config.promptCache === false.
+ if (this.config.promptCache !== false && systemText.length > 0) {
+ anthropicRequest.system = [{ type: 'text', text: systemText, cache_control: { type: 'ephemeral' } }];
+ } else {
+ anthropicRequest.system = systemText;
+ }
+ }
+
+ // Second cache breakpoint at the last message, so the growing conversation
+ // prefix is also cached turn-over-turn (system + trailing-context strategy).
+ if (this.config.promptCache !== false && messages.length > 0) {
+ const last = messages[messages.length - 1];
+ const blocks: Array<{ type: string; text?: string; source?: unknown; cache_control?: CacheControl }> =
+ typeof last.content === 'string'
+ ? [{ type: 'text', text: last.content }]
+ : last.content;
+ if (blocks.length > 0) {
+ blocks[blocks.length - 1] = { ...blocks[blocks.length - 1], cache_control: { type: 'ephemeral' } };
+ last.content = blocks;
+ }
}
if (request.temperature !== undefined) {
diff --git a/v3/@claude-flow/providers/src/types.ts b/v3/@claude-flow/providers/src/types.ts
index f9d23d25e1..98d559a504 100644
--- a/v3/@claude-flow/providers/src/types.ts
+++ b/v3/@claude-flow/providers/src/types.ts
@@ -120,6 +120,14 @@ export interface LLMProviderConfig {
// Provider-specific options
providerOptions?: Record<string, unknown>;
+ /**
+ * Anthropic prompt caching (default: enabled). When true/undefined, the
+ * provider marks the system prompt + trailing message as ephemeral cache
+ * breakpoints so repeated-prefix multi-turn calls hit the prompt cache
+ * (~90% discount on cached input tokens). Set false to disable.
+ */
+ promptCache?: boolean;
+
// Performance settings
timeout?: number;
retryAttempts?: number;