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: honour retry/retention/shutdown timer contracts; hermetic statusline format test

ruv09c2f400b18a
diff --git a/v3/@claude-flow/cli/__tests__/production-monitoring-retention-3855.test.ts b/v3/@claude-flow/cli/__tests__/production-monitoring-retention-3855.test.ts
new file mode 100644
index 0000000000..2e5d4a57dc
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/production-monitoring-retention-3855.test.ts
@@ -0,0 +1,56 @@
+/**
+ * #3855 - MonitoringHooks must honour retentionMs on reads, not only on writes.
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { MonitoringHooks } from '../src/production/monitoring.js';
+
+describe('MonitoringHooks retention on read (#3855)', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it('expired metrics disappear from getMetrics/getMetricsSummary without new writes', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1_000_000);
+ const m = new MonitoringHooks({ retentionMs: 30 });
+ m.gauge('a', 1);
+ m.gauge('b', 2);
+ expect(m.getMetrics('a')).toHaveLength(1);
+ expect(Object.keys(m.getMetricsSummary()).sort()).toEqual(['a', 'b']);
+
+ vi.setSystemTime(1_000_050);
+ expect(m.getMetrics('a')).toEqual([]);
+ expect(m.getMetrics('b')).toEqual([]);
+ expect(m.getMetricsSummary()).toEqual({});
+ });
+
+ it('summary alone (no prior getMetrics call) also drops expired metrics', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(3_000_000);
+ const m = new MonitoringHooks({ retentionMs: 30 });
+ m.gauge('a', 1);
+ expect(Object.keys(m.getMetricsSummary())).toEqual(['a']);
+ vi.setSystemTime(3_000_050);
+ expect(m.getMetricsSummary()).toEqual({});
+ });
+
+ it('getMetrics alone also drops expired metrics', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(4_000_000);
+ const m = new MonitoringHooks({ retentionMs: 30 });
+ m.gauge('a', 1);
+ vi.setSystemTime(4_000_050);
+ expect(m.getMetrics('a')).toEqual([]);
+ });
+
+ it('fresh metrics are kept; only the elapsed ones expire', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(2_000_000);
+ const m = new MonitoringHooks({ retentionMs: 100 });
+ m.gauge('old', 1);
+ vi.setSystemTime(2_000_080);
+ m.gauge('new', 2);
+ vi.setSystemTime(2_000_150);
+ expect(m.getMetrics('old')).toEqual([]);
+ expect(m.getMetrics('new')).toHaveLength(1);
+ expect(Object.keys(m.getMetricsSummary())).toEqual(['new']);
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/production-retry-jitter-3853.test.ts b/v3/@claude-flow/cli/__tests__/production-retry-jitter-3853.test.ts
new file mode 100644
index 0000000000..1d283db2e8
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/production-retry-jitter-3853.test.ts
@@ -0,0 +1,72 @@
+/**
+ * #3853 - withRetry must never wait longer than maxDelayMs, jitter included.
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { withRetry, type RetryStrategy } from '../src/production/retry.js';
+
+const STRATEGIES: RetryStrategy[] = ['exponential', 'linear', 'constant', 'fibonacci'];
+
+describe('withRetry jitter honours maxDelayMs (#3853)', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+
+ for (const strategy of STRATEGIES) {
+ it(`${strategy}: high jitter sample never exceeds the cap`, async () => {
+ vi.useFakeTimers();
+ vi.spyOn(Math, 'random').mockReturnValue(0.999);
+ let calls = 0;
+ const seen: number[] = [];
+ const p = withRetry(
+ async () => {
+ if (++calls < 2) throw new Error('boom');
+ return 'ok';
+ },
+ {
+ maxAttempts: 3, initialDelayMs: 100, maxDelayMs: 100, jitter: 0.5,
+ onRetry: (_e, _a, d) => seen.push(d),
+ },
+ strategy,
+ );
+ await vi.advanceTimersByTimeAsync(1);
+ expect(seen).toEqual([100]); // checked before the wait so a regression fails fast, not by hanging
+ await vi.advanceTimersByTimeAsync(100);
+ const r = await p;
+ expect(r.success).toBe(true);
+ expect(r.retryHistory.map(h => h.delayMs)).toEqual([100]);
+ });
+ }
+
+ it('negative jitter still reduces the delay below the cap', async () => {
+ vi.useFakeTimers();
+ vi.spyOn(Math, 'random').mockReturnValue(0);
+ const seen: number[] = [];
+ let calls = 0;
+ const p = withRetry(
+ async () => { if (++calls < 2) throw new Error('x'); return 1; },
+ { initialDelayMs: 100, maxDelayMs: 100, jitter: 0.5, onRetry: (_e, _a, d) => seen.push(d) },
+ 'constant',
+ );
+ await vi.advanceTimersByTimeAsync(1);
+ expect(seen).toEqual([50]);
+ await vi.advanceTimersByTimeAsync(100);
+ await p;
+ });
+
+ it('delay below the cap keeps its jitter (cap not applied early)', async () => {
+ vi.useFakeTimers();
+ vi.spyOn(Math, 'random').mockReturnValue(0.999);
+ const seen: number[] = [];
+ let calls = 0;
+ const p = withRetry(
+ async () => { if (++calls < 2) throw new Error('x'); return 1; },
+ { initialDelayMs: 100, maxDelayMs: 1000, jitter: 0.5, onRetry: (_e, _a, d) => seen.push(d) },
+ 'constant',
+ );
+ await vi.advanceTimersByTimeAsync(1);
+ expect(seen).toEqual([150]);
+ await vi.advanceTimersByTimeAsync(200);
+ await p;
+ });
+});
diff --git a/v3/@claude-flow/cli/__tests__/worker-queue-shutdown-timers-3841.test.ts b/v3/@claude-flow/cli/__tests__/worker-queue-shutdown-timers-3841.test.ts
new file mode 100644
index 0000000000..b136930716
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/worker-queue-shutdown-timers-3841.test.ts
@@ -0,0 +1,48 @@
+/**
+ * #3841 - WorkerQueue.shutdown() must release scheduled retry timers.
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { WorkerQueue } from '../src/services/worker-queue.js';
+
+describe('WorkerQueue shutdown releases retry timers (#3841)', () => {
+ afterEach(() => vi.useRealTimers());
+
+ async function failedOnce() {
+ const q = new WorkerQueue();
+ await q.initialize();
+ await q.enqueue('audit', {});
+ const task = await q.dequeue(['audit']);
+ expect(task).not.toBeNull();
+ const before = vi.getTimerCount();
+ await q.fail(task!.id, 'transient', true); // schedules exactly one retry timer
+ expect(vi.getTimerCount()).toBe(before + 1);
+ return q;
+ }
+
+ it('leaves no pending timers after shutdown', async () => {
+ vi.useFakeTimers();
+ const q = await failedOnce();
+ await q.shutdown();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('does not push work into the stopped queue after shutdown', async () => {
+ vi.useFakeTimers();
+ const q = await failedOnce();
+ await q.shutdown();
+ await vi.advanceTimersByTimeAsync(60_000);
+ // nothing was pushed into the stopped queue's store by a surviving retry callback
+ const store = (q as unknown as { store: { popFromQueue(name: string): string | null } }).store;
+ expect(store.popFromQueue('claude-flow:queue:audit')).toBeNull();
+ });
+
+ it('a retry still fires normally when no shutdown happens', async () => {
+ vi.useFakeTimers();
+ const q = await failedOnce();
+ await vi.advanceTimersByTimeAsync(2_001);
+ const t = await q.dequeue(['audit']);
+ expect(t?.retryCount).toBe(1);
+ await q.fail(t!.id, 'done', false);
+ await q.shutdown();
+ });
+});
diff --git a/v3/@claude-flow/cli/src/production/monitoring.ts b/v3/@claude-flow/cli/src/production/monitoring.ts
index d3914096af..15298fad19 100644
--- a/v3/@claude-flow/cli/src/production/monitoring.ts
+++ b/v3/@claude-flow/cli/src/production/monitoring.ts
@@ -354,6 +354,7 @@ export class MonitoringHooks {
* Get metrics for a specific name
*/
getMetrics(name: string, since?: number): MetricEvent[] {
+ this.expireMetrics();
let filtered = this.metrics.filter(m => m.name === name);
if (since) {
filtered = filtered.filter(m => m.timestamp >= since);
@@ -365,6 +366,7 @@ export class MonitoringHooks {
* Get all metrics summary
*/
getMetricsSummary(): Record<string, { count: number; lastValue: number; avgValue: number }> {
+ this.expireMetrics();
const summary: Record<string, { count: number; sum: number; lastValue: number }> = {};
for (const metric of this.metrics) {
@@ -443,12 +445,15 @@ export class MonitoringHooks {
}
}
- private cleanupMetrics(): void {
- const now = Date.now();
- const cutoff = now - this.config.retentionMs;
+ /** Drop metrics older than retentionMs (also applied on reads, #3855). */
+ private expireMetrics(): void {
+ const cutoff = Date.now() - this.config.retentionMs;
+ this.metrics = this.metrics.filter(m => m.timestamp > cutoff);
+ }
+ private cleanupMetrics(): void {
// Remove old metrics
- this.metrics = this.metrics.filter(m => m.timestamp > cutoff);
+ this.expireMetrics();
// Limit total metrics
if (this.metrics.length > this.config.maxMetrics) {
diff --git a/v3/@claude-flow/cli/src/production/retry.ts b/v3/@claude-flow/cli/src/production/retry.ts
index ff85251497..d0ca342a75 100644
--- a/v3/@claude-flow/cli/src/production/retry.ts
+++ b/v3/@claude-flow/cli/src/production/retry.ts
@@ -103,6 +103,9 @@ function calculateDelay(
delay += (Math.random() - 0.5) * 2 * jitterRange;
}
+ // Enforce the configured maximum on the final (jittered) delay
+ delay = Math.min(delay, config.maxDelayMs);
+
return Math.round(Math.max(0, delay));
}
diff --git a/v3/@claude-flow/cli/src/services/worker-queue.ts b/v3/@claude-flow/cli/src/services/worker-queue.ts
index fedfc76db3..8f31a73924 100644
--- a/v3/@claude-flow/cli/src/services/worker-queue.ts
+++ b/v3/@claude-flow/cli/src/services/worker-queue.ts
@@ -276,6 +276,7 @@ export class WorkerQueue extends EventEmitter {
private workerId: string;
private heartbeatTimer?: NodeJS.Timeout;
private processingTasks: Set<string> = new Set();
+ private retryTimers: Set<NodeJS.Timeout> = new Set();
private isShuttingDown = false;
private maxConcurrent = 1;
private initialized = false;
@@ -431,10 +432,13 @@ export class WorkerQueue extends EventEmitter {
// Re-queue with delay (exponential backoff)
const delay = Math.min(30000, 1000 * Math.pow(2, task.retryCount));
- setTimeout(() => {
+ // Tracked so shutdown() can release it
+ const timer = setTimeout(() => {
+ this.retryTimers.delete(timer);
const queueName = this.getQueueName(task.workerType);
this.store.pushToQueue(queueName, taskId, PRIORITY_SCORES[task.priority]);
}, delay);
+ this.retryTimers.add(timer);
this.emit('taskRetrying', { taskId, retryCount: task.retryCount, delay });
} else {
@@ -653,6 +657,10 @@ export class WorkerQueue extends EventEmitter {
await this.fail(taskId, 'Worker shutdown', false);
}
+ // Release scheduled retry timers (they would hold the process open)
+ for (const timer of this.retryTimers) clearTimeout(timer);
+ this.retryTimers.clear();
+
// Stop store cleanup
this.store.stopCleanup();
diff --git a/v3/@claude-flow/hooks/__tests__/statusline/statusline-collision.test.ts b/v3/@claude-flow/hooks/__tests__/statusline/statusline-collision.test.ts
index 6d2ab7f003..755f0490ea 100644
--- a/v3/@claude-flow/hooks/__tests__/statusline/statusline-collision.test.ts
+++ b/v3/@claude-flow/hooks/__tests__/statusline/statusline-collision.test.ts
@@ -9,7 +9,34 @@
* content there.
*/
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, afterEach } from 'vitest';
+
+// Hermetic: the formatter must never shell out (live `gh api user`, `ps`, `git`) in
+// these formatting-only tests; every dynamic value comes through the public
+// registerDataSources seam. #3844
+vi.mock('child_process', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('child_process')>();
+ return { ...actual, execSync: vi.fn(() => '') };
+});
+
+// Imported at collection time so the cold import is not charged to the first timed case.
+import { execSync } from 'child_process';
+import { StatuslineGenerator } from '../../src/statusline/index.js';
+
+function createGenerator(): StatuslineGenerator {
+ const generator = new StatuslineGenerator();
+ generator.registerDataSources({
+ getUserInfo: () => ({ name: 'test-user', gitBranch: 'main', modelName: 'test-model' }),
+ getSystemMetrics: () => ({ memoryMB: 100, contextPct: 10, intelligencePct: 50, subAgents: 0 }),
+ getSwarmActivity: () => ({ activeAgents: 0, maxAgents: 15, coordinationActive: false }),
+ });
+ return generator;
+}
+
+afterEach(() => {
+ expect(execSync).not.toHaveBeenCalled();
+ vi.mocked(execSync).mockClear();
+});
/**
* Strip ANSI escape codes from a string
@@ -77,11 +104,8 @@ function isCollisionZoneClear(line: string): boolean {
}
describe('Statusline Collision Zone Avoidance', () => {
- it('should have clear collision zone in safe multi-line output', async () => {
- // Import dynamically to avoid build issues
- const { StatuslineGenerator } = await import('../../src/statusline/index.js');
-
- const generator = new StatuslineGenerator();
+ it('should have clear collision zone in safe multi-line output', () => {
+ const generator = createGenerator();
const output = generator.generateSafeStatusline();
if (!output) {
@@ -99,10 +123,8 @@ describe('Statusline Collision Zone Avoidance', () => {
}
});
- it('should produce single-line output when requested', async () => {
- const { StatuslineGenerator } = await import('../../src/statusline/index.js');
-
- const generator = new StatuslineGenerator();
+ it('should produce single-line output when requested', () => {
+ const generator = createGenerator();
const output = generator.generateSingleLine();
if (!output) {
@@ -113,10 +135,8 @@ describe('Statusline Collision Zone Avoidance', () => {
expect(output.includes('\n')).toBe(false);
});
- it('should have padding in the collision line', async () => {
- const { StatuslineGenerator } = await import('../../src/statusline/index.js');
-
- const generator = new StatuslineGenerator();
+ it('should have padding in the collision line', () => {
+ const generator = createGenerator();
const output = generator.generateSafeStatusline();
if (!output) {
@@ -144,10 +164,8 @@ describe('Statusline Collision Zone Avoidance', () => {
});
describe('Statusline Output Modes', () => {
- it('should support all output modes', async () => {
- const { StatuslineGenerator } = await import('../../src/statusline/index.js');
-
- const generator = new StatuslineGenerator();
+ it('should support all output modes', () => {
+ const generator = createGenerator();
// Regular statusline
const regular = generator.generateStatusline();