π 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): make `hooks intelligence --train` actually train (#2940) (#2988)
rUv1e2178f24635
diff --git a/v3/@claude-flow/cli/__tests__/hooks-intelligence-train-2940.test.ts b/v3/@claude-flow/cli/__tests__/hooks-intelligence-train-2940.test.tsnew file mode 100644index 0000000000..12d6f535ae--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/hooks-intelligence-train-2940.test.ts@@ -0,0 +1,80 @@+/**+ * #2940: `hooks intelligence --train` exited 0 and printed a full success+ * dashboard (Neural Persistence + V3 Performance Gains tables) without ever+ * training anything. The `--train` handler (`hooks_intelligence` MCP tool)+ * declared a `forceTraining` input but never read it β `commands/hooks.ts`'s+ * CLI action just slept 500ms and printed a canned "Training cycle+ * completed". `lastAdaptation` (what `--status` reports as "Last Training")+ * never moved, so it could only ever *age*, no matter how many times+ * `--train` ran β a naive read looked like "the number changed" when it had+ * changed in the wrong direction.+ *+ * Fixed by actually calling `distillLearning()` (memory/intelligence.ts,+ * already existed and already bumps `lastAdaptation` when it runs) from the+ * `hooks_intelligence` handler when `forceTraining` is set, and reporting+ * what happened instead of a fixed message: distilled N patterns, ran with+ * nothing new to distill, or could not run.+ *+ * Black-box against the real built CLI β same pattern as+ * mcp-http-foreground-2984.test.ts β because the bug is in how two command+ * modules communicate a real outcome through the MCP-tool boundary, not+ * pure logic a unit test could isolate.+ */+import { describe, it, expect } from 'vitest';+import { spawnSync } from 'child_process';+import { existsSync, mkdtempSync, rmSync } from 'fs';+import { fileURLToPath } from 'url';+import { join } from 'path';+import { tmpdir } from 'os';++const CLI_BIN = fileURLToPath(new URL('../bin/cli.js', import.meta.url));+const CLI_BUILT = existsSync(CLI_BIN);++// `output.printWarning` writes to stderr β merge both streams so assertions+// can see a warning-path message the same way a terminal user would.+function cli(args: string[], cwd: string): { out: string; code: number } {+ const result = spawnSync(process.execPath, [CLI_BIN, ...args], {+ encoding: 'utf-8',+ timeout: 30_000,+ cwd,+ });+ return { out: `${result.stdout ?? ''}${result.stderr ?? ''}`, code: result.status ?? 1 };+}++function lastTrainingSeconds(statusOut: string): number | null {+ const m = statusOut.match(/Last Training:\s*(?:(\d+)s ago|(Never))/);+ if (!m) return null;+ if (m[2]) return null; // "Never"+ return Number(m[1]);+}++describe.skipIf(!CLI_BUILT)('#2940 hooks intelligence --train actually trains', () => {+ it('moves "Last Training" to ~0s ago instead of only ever aging', () => {+ const cwd = mkdtempSync(join(tmpdir(), 'ruflo-2940-'));+ try {+ const init = cli(['memory', 'init'], cwd);+ expect(init.code).toBe(0);++ const before = cli(['hooks', 'intelligence', '--status'], cwd);+ expect(before.code).toBe(0);+ expect(lastTrainingSeconds(before.out)).toBeNull(); // "Never" β no training has run yet++ const trained = cli(['hooks', 'intelligence', '--train'], cwd);+ expect(trained.code).toBe(0);+ // Pre-fix: this printed the exact same "Training cycle completed" no+ // matter what happened. Post-fix: it's conditioned on a real outcome,+ // so it always contains one of these two honest phrases.+ expect(trained.out).toMatch(/Training cycle completed|Training cycle ran/);++ const after = cli(['hooks', 'intelligence', '--status'], cwd);+ expect(after.code).toBe(0);+ const seconds = lastTrainingSeconds(after.out);+ // Pre-fix: still "Never" (lastAdaptation was never written) β the+ // defect this test pins. Post-fix: a fresh, small elapsed time.+ expect(seconds).not.toBeNull();+ expect(seconds as number).toBeLessThan(30);+ } finally {+ rmSync(cwd, { recursive: true, force: true });+ }+ }, 60_000);+});diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.tsindex 5dd7954ff0..5f8ac08fe3 100644--- a/v3/@claude-flow/cli/src/commands/hooks.ts+++ b/v3/@claude-flow/cli/src/commands/hooks.ts@@ -2645,7 +2645,12 @@ const intelligenceCommand: Command = {tokenReduction: 'N/A',sweBenchScore: 'N/A',},- lastTrainingMs: lastAdaptation ? Date.now() - lastAdaptation : undefined,+ // #2940: a training cycle that actually ran this invocation is "now"+ // β reading the pre-call `lastAdaptation` here would still show the+ // stale age (the exact "aged instead of reset" symptom reported).+ lastTrainingMs: (mcpResult as { training?: { trained?: boolean } } | null)?.training?.trained+ ? 0+ : (lastAdaptation ? Date.now() - lastAdaptation : undefined),persistence: {dataDir: persistence.dataDir,patternsFile: persistence.patternsFile,@@ -2658,10 +2663,33 @@ const intelligenceCommand: Command = {},};+ // #2940: this block used to be a cosmetic 500ms sleep followed by an+ // unconditional "Training cycle completed" β no training ever ran and+ // `lastAdaptation` never moved, so `--status` could never report a+ // training cycle as recent no matter how many times `--train` was+ // invoked. `hooks_intelligence` now actually distills when asked+ // (see mcp-tools/hooks-tools.ts); report what it actually did instead+ // of a canned success message.+ const trainingResult = (mcpResult as { training?: { attempted: boolean; trained: boolean; patternsDistilled?: number; reason?: string } } | null)?.training;if (forceTraining) {- spinner.setText('Running training cycle...');- await new Promise(resolve => setTimeout(resolve, 500));- spinner.succeed('Training cycle completed');+ if (trainingResult?.trained && trainingResult.patternsDistilled) {+ spinner.succeed(+ `Training cycle completed β distilled ${trainingResult.patternsDistilled} pattern${trainingResult.patternsDistilled === 1 ? '' : 's'}`+ );+ } else if (trainingResult?.trained) {+ // Ran (SONA/EWC++ distillation pass executed, lastAdaptation+ // moved) but found zero new patterns β deliberately NOT the same+ // message as a real distillation, or this is exactly the "success+ // report with no state change behind it" the issue describes.+ spinner.stop();+ output.printWarning(`Training cycle ran β 0 new patterns to distill (${trainingResult.reason || 'nothing new since the last cycle'})`);+ } else if (trainingResult?.attempted) {+ spinner.stop();+ output.printWarning(`Training cycle ran with nothing to do β ${trainingResult.reason || 'no new trajectories to distill'}`);+ } else {+ spinner.stop();+ output.printWarning('Training cycle could not run β intelligence MCP tool unavailable');+ }} else {spinner.succeed(hasLocalData ? 'Intelligence system active (local data loaded)' : 'Intelligence system active');}diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.tsindex b2caf8baa2..027363fbb9 100644--- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts@@ -2496,7 +2496,39 @@ export const hooksIntelligence: MCPTool = {const ewcAvailable = (await getEWCConsolidator()) !== null;const loraAvailable = (await getLoRAAdapter()) !== null;+ // #2940: `forceTraining` (CLI `hooks intelligence --train`) was declared+ // on this tool's input schema but never read β the handler always+ // returned the same read-only status dashboard, so `lastAdaptation`+ // (what `--status` reports as "Last Training") could never move no+ // matter how many times `--train` ran. Actually distill when asked,+ // and report honestly rather than always implying success:+ // `attempted: false` (flag not passed), `trained: true` (real work+ // happened, lastAdaptation now current), or `trained: false` with a+ // reason (nothing new to distill, or distillation unavailable).+ const training: { attempted: boolean; trained: boolean; patternsDistilled?: number; ewcPenalty?: number; reason?: string } =+ { attempted: false, trained: false };+ if (params.forceTraining) {+ training.attempted = true;+ try {+ const { distillLearning } = await import('../memory/intelligence.js');+ const result = await distillLearning();+ if (result) {+ training.trained = true;+ training.patternsDistilled = result.patternsDistilled;+ training.ewcPenalty = result.ewcPenalty;+ if (result.patternsDistilled === 0) {+ training.reason = 'no new trajectories to distill since the last training cycle';+ }+ } else {+ training.reason = 'intelligence system unavailable β could not initialize SONA/ReasoningBank';+ }+ } catch (error) {+ training.reason = `distillation failed: ${error instanceof Error ? error.message : String(error)}`;+ }+ }+return {+ training,mode,status: 'active',components: {