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(daemon): CPU-proportional maxCpuLoad replaces hardcoded 2.0 (rebased from #1353) (#1369)

rUv100ffeaa3542
diff --git a/.gitignore b/.gitignore
index 21d1b4e251..b7fc199d48 100644
--- a/.gitignore
+++ b/.gitignore
@@ -67,6 +67,7 @@
.mcp.json
.nyc_output/
.pnpm-debug.log*
+.pnpm-store/
.research/
.roo/
.roomodes
diff --git a/v3/@claude-flow/cli/__tests__/services/worker-daemon-resource-thresholds.test.ts b/v3/@claude-flow/cli/__tests__/services/worker-daemon-resource-thresholds.test.ts
new file mode 100644
index 0000000000..9e03189de5
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/services/worker-daemon-resource-thresholds.test.ts
@@ -0,0 +1,746 @@
+/**
+ * WorkerDaemon Resource Thresholds Tests
+ *
+ * Validates CPU-proportional defaults, config priority chain,
+ * state persistence, resource gating, and input validation.
+ *
+ * Uses real temp directories for filesystem isolation.
+ * All resource gating tests use explicit constructor config
+ * to avoid host-machine dependency.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { WorkerDaemon } from '../../src/services/worker-daemon.js';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir, cpus } from 'os';
+
+describe('WorkerDaemon resource thresholds', () => {
+ let tempDir: string;
+
+ beforeEach(() => {
+ tempDir = mkdtempSync(join(tmpdir(), 'worker-daemon-test-'));
+ mkdirSync(join(tempDir, '.claude-flow', 'logs'), { recursive: true });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.doUnmock('os');
+ rmSync(tempDir, { recursive: true, force: true });
+ // Clean up signal listeners to prevent MaxListenersExceededWarning
+ process.removeAllListeners('SIGTERM');
+ process.removeAllListeners('SIGINT');
+ process.removeAllListeners('SIGHUP');
+ });
+
+ // =========================================================================
+ // Smart CPU-proportional defaults
+ // =========================================================================
+ describe('smart CPU-proportional defaults', () => {
+ it('should compute maxCpuLoad as max(cpuCount * 0.8, 2.0)', () => {
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ const cpuCount = cpus().length || 1;
+ const expected = Math.max(cpuCount * 0.8, 2.0);
+
+ expect(config.resourceThresholds.maxCpuLoad).toBeCloseTo(expected, 1);
+ });
+
+ it('should always be at least 2.0 regardless of CPU count', () => {
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ expect(config.resourceThresholds.maxCpuLoad).toBeGreaterThanOrEqual(2.0);
+ });
+
+ it('should scale above 2.0 on multi-core machines', () => {
+ const cpuCount = cpus().length;
+ if (cpuCount <= 3) return; // skip on small machines
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ expect(config.resourceThresholds.maxCpuLoad).toBeGreaterThan(2.0);
+ });
+
+ it('should use platform-aware default for minFreeMemoryPercent', () => {
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ const expectedMinFreeMem = process.platform === 'darwin' ? 5 : 10;
+ expect(config.resourceThresholds.minFreeMemoryPercent).toBe(expectedMinFreeMem);
+ });
+ });
+
+ // =========================================================================
+ // Resource gating via canRunWorker
+ // =========================================================================
+ describe('resource gating', () => {
+ it('should allow workers when CPU load is below threshold', async () => {
+ // Explicitly set threshold β€” decoupled from host machine
+ const daemon = new WorkerDaemon(tempDir, {
+ resourceThresholds: { maxCpuLoad: 9.6, minFreeMemoryPercent: 20 },
+ });
+
+ vi.doMock('os', () => ({
+ default: {
+ loadavg: () => [3.5, 3.0, 2.5],
+ totalmem: () => 16e9,
+ freemem: () => 8e9, // 50% free
+ },
+ loadavg: () => [3.5, 3.0, 2.5],
+ totalmem: () => 16e9,
+ freemem: () => 8e9,
+ }));
+
+ const result = await (daemon as any).canRunWorker();
+ expect(result.allowed).toBe(true);
+ });
+
+ it('should block workers when CPU load exceeds threshold', async () => {
+ const daemon = new WorkerDaemon(tempDir, {
+ resourceThresholds: { maxCpuLoad: 2.0, minFreeMemoryPercent: 5 },
+ });
+
+ vi.doMock('os', () => ({
+ default: {
+ loadavg: () => [5.0, 4.0, 3.0],
+ totalmem: () => 16e9,
+ freemem: () => 8e9,
+ },
+ loadavg: () => [5.0, 4.0, 3.0],
+ totalmem: () => 16e9,
+ freemem: () => 8e9,
+ }));
+
+ const result = await (daemon as any).canRunWorker();
+ expect(result.allowed).toBe(false);
+ expect(result.reason).toContain('CPU');
+ });
+
+ it('should block workers when free memory is below threshold', async () => {
+ const daemon = new WorkerDaemon(tempDir, {
+ resourceThresholds: { maxCpuLoad: 100, minFreeMemoryPercent: 50 },
+ });
+
+ vi.doMock('os', () => ({
+ default: {
+ loadavg: () => [0.5, 0.5, 0.5],
+ totalmem: () => 16e9,
+ freemem: () => 1e9, // ~6% free β€” below 50% threshold
+ },
+ loadavg: () => [0.5, 0.5, 0.5],
+ totalmem: () => 16e9,
+ freemem: () => 1e9,
+ }));
+
+ const result = await (daemon as any).canRunWorker();
+ expect(result.allowed).toBe(false);
+ expect(result.reason.toLowerCase()).toContain('memory');
+ });
+ });
+
+ // =========================================================================
+ // Config file reading
+ // =========================================================================
+ describe('config.json reading', () => {
+ it('should read daemon settings from flat dot-notation keys', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.resourceThresholds.maxCpuLoad': 10,
+ 'daemon.resourceThresholds.minFreeMemoryPercent': 25,
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ expect(config.resourceThresholds.maxCpuLoad).toBe(10);
+ expect(config.resourceThresholds.minFreeMemoryPercent).toBe(25);
+ });
+
+ it('should read daemon settings from scopes.project', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ scopes: {
+ project: {
+ 'daemon.resourceThresholds.maxCpuLoad': 12,
+ },
+ },
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ expect(config.resourceThresholds.maxCpuLoad).toBe(12);
+ });
+
+ it('should handle malformed config.json gracefully', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, '{ invalid json !!!');
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ const expectedMinFreeMem = process.platform === 'darwin' ? 5 : 10;
+ expect(config.resourceThresholds.maxCpuLoad).toBeGreaterThanOrEqual(2.0);
+ expect(config.resourceThresholds.minFreeMemoryPercent).toBe(expectedMinFreeMem);
+ });
+ });
+
+ // =========================================================================
+ // Config priority chain
+ // =========================================================================
+ describe('config priority: constructor arg > config.json > smart default', () => {
+ it('should prefer constructor arg over config.json', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.resourceThresholds.maxCpuLoad': 10,
+ }));
+
+ const daemon = new WorkerDaemon(tempDir, {
+ resourceThresholds: { maxCpuLoad: 15, minFreeMemoryPercent: 5 },
+ });
+ const config = daemon.getStatus().config;
+
+ expect(config.resourceThresholds.maxCpuLoad).toBe(15);
+ });
+
+ it('should prefer config.json over smart default', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.resourceThresholds.maxCpuLoad': 42,
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ expect(config.resourceThresholds.maxCpuLoad).toBe(42);
+ });
+ });
+
+ // =========================================================================
+ // State persistence
+ // =========================================================================
+ describe('state persistence', () => {
+ it('should restore resourceThresholds from daemon-state.json', () => {
+ const stateFile = join(tempDir, '.claude-flow', 'daemon-state.json');
+ writeFileSync(stateFile, JSON.stringify({
+ running: false,
+ workers: {},
+ config: {
+ resourceThresholds: { maxCpuLoad: 8.0, minFreeMemoryPercent: 15 },
+ workers: [],
+ },
+ savedAt: new Date().toISOString(),
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ expect(config.resourceThresholds.maxCpuLoad).toBe(8.0);
+ expect(config.resourceThresholds.minFreeMemoryPercent).toBe(15);
+ });
+
+ it('should restore maxConcurrent and workerTimeoutMs from state', () => {
+ const stateFile = join(tempDir, '.claude-flow', 'daemon-state.json');
+ writeFileSync(stateFile, JSON.stringify({
+ running: false,
+ workers: {},
+ config: {
+ maxConcurrent: 6,
+ workerTimeoutMs: 600000,
+ resourceThresholds: { maxCpuLoad: 10.0, minFreeMemoryPercent: 10 },
+ workers: [],
+ },
+ savedAt: new Date().toISOString(),
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ expect(config.maxConcurrent).toBe(6);
+ expect(config.workerTimeoutMs).toBe(600000);
+ });
+
+ it('should reject invalid values from saved state', () => {
+ const stateFile = join(tempDir, '.claude-flow', 'daemon-state.json');
+ writeFileSync(stateFile, JSON.stringify({
+ running: false,
+ workers: {},
+ config: {
+ resourceThresholds: { maxCpuLoad: -10, minFreeMemoryPercent: 200 },
+ maxConcurrent: 0,
+ workerTimeoutMs: -500,
+ workers: [],
+ },
+ savedAt: new Date().toISOString(),
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ expect(config.resourceThresholds.maxCpuLoad).toBeGreaterThan(0);
+ expect(config.resourceThresholds.minFreeMemoryPercent).toBeLessThanOrEqual(100);
+ expect(config.maxConcurrent).toBeGreaterThan(0);
+ expect(config.workerTimeoutMs).toBeGreaterThan(0);
+ });
+ });
+
+ // =========================================================================
+ // Input validation
+ // =========================================================================
+ describe('input validation', () => {
+ it('should ignore non-numeric values in config.json', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.resourceThresholds.maxCpuLoad': 'not-a-number',
+ 'daemon.resourceThresholds.minFreeMemoryPercent': null,
+ 'daemon.maxConcurrent': true,
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ const expectedMinFreeMem = process.platform === 'darwin' ? 5 : 10;
+ expect(typeof config.resourceThresholds.maxCpuLoad).toBe('number');
+ expect(config.resourceThresholds.maxCpuLoad).toBeGreaterThanOrEqual(2.0);
+ expect(config.resourceThresholds.minFreeMemoryPercent).toBe(expectedMinFreeMem);
+ expect(config.maxConcurrent).toBe(2); // default
+ });
+
+ it('should ignore negative values in config.json', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.resourceThresholds.maxCpuLoad': -5,
+ 'daemon.maxConcurrent': -1,
+ 'daemon.workerTimeoutMs': -100,
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ expect(config.resourceThresholds.maxCpuLoad).toBeGreaterThan(0);
+ expect(config.maxConcurrent).toBeGreaterThan(0);
+ expect(config.workerTimeoutMs).toBeGreaterThan(0);
+ });
+
+ it('should reject minFreeMemoryPercent outside 0-100 range', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.resourceThresholds.minFreeMemoryPercent': 150,
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ expect(config.resourceThresholds.minFreeMemoryPercent).toBeLessThanOrEqual(100);
+ });
+ });
+
+ // =========================================================================
+ // processPendingWorkers busy-wait fix (WI-1 / PR #1052)
+ // =========================================================================
+ describe('processPendingWorkers busy-wait prevention', () => {
+ it('should not spin when all workers are deferred due to resource pressure', async () => {
+ // Set impossibly low thresholds so canRunWorker always rejects
+ const daemon = new WorkerDaemon(tempDir, {
+ maxConcurrent: 2,
+ resourceThresholds: { maxCpuLoad: 0.001, minFreeMemoryPercent: 99.99 },
+ });
+
+ // Seed the pending queue with a worker
+ const pendingWorkers = (daemon as any).pendingWorkers as string[];
+ pendingWorkers.push('map');
+
+ // Spy on executeWorkerWithConcurrencyControl to count invocations
+ const execSpy = vi.spyOn(daemon as any, 'executeWorkerWithConcurrencyControl');
+
+ await (daemon as any).processPendingWorkers();
+
+ // Should have been called exactly once β€” then broke out of the loop
+ expect(execSpy.mock.calls.length).toBe(1);
+ // The deferred worker should still be on the pending queue (pushed back by executeWorkerWithConcurrencyControl)
+ expect(pendingWorkers).toContain('map');
+ });
+
+ it('should schedule a backoff retry when no workers are running and a worker is deferred', async () => {
+ const daemon = new WorkerDaemon(tempDir, {
+ maxConcurrent: 2,
+ resourceThresholds: { maxCpuLoad: 0.001, minFreeMemoryPercent: 99.99 },
+ });
+
+ const pendingWorkers = (daemon as any).pendingWorkers as string[];
+ pendingWorkers.push('audit');
+
+ // Ensure no workers are currently running
+ expect((daemon as any).runningWorkers.size).toBe(0);
+
+ const setTimeoutSpy = vi.spyOn(global, 'setTimeout');
+ const callCountBefore = setTimeoutSpy.mock.calls.length;
+
+ await (daemon as any).processPendingWorkers();
+
+ // Find the 30-second backoff call among any setTimeout calls
+ const backoffCalls = setTimeoutSpy.mock.calls
+ .slice(callCountBefore)
+ .filter((call) => call[1] === 30_000);
+ expect(backoffCalls.length).toBe(1);
+
+ setTimeoutSpy.mockRestore();
+ });
+
+ it('should not schedule backoff when running workers will drain the queue', async () => {
+ const daemon = new WorkerDaemon(tempDir, {
+ maxConcurrent: 1,
+ resourceThresholds: { maxCpuLoad: 0.001, minFreeMemoryPercent: 99.99 },
+ });
+
+ // Simulate a worker already running β€” its finally block will re-trigger processPendingWorkers
+ (daemon as any).runningWorkers.add('optimize');
+
+ const pendingWorkers = (daemon as any).pendingWorkers as string[];
+ pendingWorkers.push('map');
+
+ const setTimeoutSpy = vi.spyOn(global, 'setTimeout');
+ const callCountBefore = setTimeoutSpy.mock.calls.length;
+
+ await (daemon as any).processPendingWorkers();
+
+ // No 30-second backoff should have been scheduled because a running worker exists
+ const backoffCalls = setTimeoutSpy.mock.calls
+ .slice(callCountBefore)
+ .filter((call) => call[1] === 30_000);
+ expect(backoffCalls.length).toBe(0);
+
+ setTimeoutSpy.mockRestore();
+ });
+ });
+
+ // =========================================================================
+ // Mutation-killing tests (Stryker-inspired)
+ // Each test targets a specific code mutation that would survive existing tests.
+ // =========================================================================
+ describe('mutation killing', () => {
+ // MUTANT: Math.max(cpuCount * 0.8, 2.0) β†’ Math.min(cpuCount * 0.8, 2.0)
+ // On 12-core: Math.min(9.6, 2.0) = 2.0 β€” would survive ">=2.0" tests
+ it('should NOT use Math.min β€” multi-core default must exceed 2.0', () => {
+ const cpuCount = cpus().length;
+ if (cpuCount <= 3) return;
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ // Kills: Math.max β†’ Math.min mutant
+ // Math.min(12*0.8, 2.0) = 2.0, but correct is 9.6
+ expect(config.resourceThresholds.maxCpuLoad).toBeGreaterThan(2.0);
+ expect(config.resourceThresholds.maxCpuLoad).toBeLessThan(cpuCount); // sanity
+ });
+
+ // MUTANT: cpuCount * 0.8 β†’ cpuCount * 0 (or cpuCount + 0.8)
+ it('should scale proportionally to CPU count, not be constant', () => {
+ const cpuCount = cpus().length;
+ if (cpuCount <= 3) return;
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ // Kills: * 0.8 β†’ * 0, + 0.8, - 0.8
+ expect(config.resourceThresholds.maxCpuLoad).toBeGreaterThan(cpuCount * 0.5);
+ expect(config.resourceThresholds.maxCpuLoad).toBeLessThan(cpuCount * 1.0);
+ });
+
+ // MUTANT: `>` β†’ `>=` in canRunWorker CPU check
+ // loadavg === maxCpuLoad should be ALLOWED (not blocked)
+ it('should allow workers when CPU load equals exactly the threshold', async () => {
+ const daemon = new WorkerDaemon(tempDir, {
+ resourceThresholds: { maxCpuLoad: 5.0, minFreeMemoryPercent: 5 },
+ });
+
+ vi.doMock('os', () => ({
+ default: {
+ loadavg: () => [5.0, 4.0, 3.0], // exactly at threshold
+ totalmem: () => 16e9,
+ freemem: () => 8e9,
+ },
+ loadavg: () => [5.0, 4.0, 3.0],
+ totalmem: () => 16e9,
+ freemem: () => 8e9,
+ }));
+
+ const result = await (daemon as any).canRunWorker();
+ // Kills: > β†’ >= mutant (at-threshold should pass)
+ expect(result.allowed).toBe(true);
+ });
+
+ // MUTANT: `<` β†’ `<=` in canRunWorker memory check
+ // freePercent === minFreeMemoryPercent should be ALLOWED
+ it('should allow workers when free memory equals exactly the threshold', async () => {
+ const daemon = new WorkerDaemon(tempDir, {
+ resourceThresholds: { maxCpuLoad: 100, minFreeMemoryPercent: 20 },
+ });
+
+ vi.doMock('os', () => ({
+ default: {
+ loadavg: () => [0.5, 0.5, 0.5],
+ totalmem: () => 100e9,
+ freemem: () => 20e9, // exactly 20% = threshold
+ },
+ loadavg: () => [0.5, 0.5, 0.5],
+ totalmem: () => 100e9,
+ freemem: () => 20e9,
+ }));
+
+ const result = await (daemon as any).canRunWorker();
+ // Kills: < β†’ <= mutant (at-threshold should pass)
+ expect(result.allowed).toBe(true);
+ });
+
+ // MUTANT: Remove `|| 1` fallback in getEffectiveCpuCount
+ // On bare metal this doesn't matter, but the floor must exist
+ it('should return at least 1 from getEffectiveCpuCount', () => {
+ const count = WorkerDaemon.getEffectiveCpuCount();
+ // Kills: removal of || 1 (result must never be 0)
+ expect(count).toBeGreaterThanOrEqual(1);
+ });
+
+ // MUTANT: Remove scopes.project fallback in readDaemonConfigFromFile
+ // Config only at scopes.project level must still be read
+ it('should prefer scopes.project over root when both exist', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.resourceThresholds.maxCpuLoad': 5,
+ scopes: {
+ project: {
+ 'daemon.resourceThresholds.maxCpuLoad': 20,
+ },
+ },
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ // Kills: removal of scopes.project ?? raw fallback
+ // scopes.project should take priority over root
+ expect(config.resourceThresholds.maxCpuLoad).toBe(20);
+ });
+
+ // MUTANT: Remove validation `rawCpuLoad > 0` β†’ accept zero
+ it('should reject maxCpuLoad of exactly 0 in config.json', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.resourceThresholds.maxCpuLoad': 0,
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ // Kills: > 0 β†’ >= 0 mutant (zero should be rejected)
+ expect(config.resourceThresholds.maxCpuLoad).toBeGreaterThan(0);
+ });
+
+ // MUTANT: Remove validation `rawMinMem <= 100`
+ it('should reject minFreeMemoryPercent of exactly 101 in config.json', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.resourceThresholds.minFreeMemoryPercent': 101,
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ // Kills: <= 100 β†’ < 100 or removal of upper bound check
+ expect(config.resourceThresholds.minFreeMemoryPercent).toBeLessThanOrEqual(100);
+ });
+
+ // MUTANT: minFreeMemoryPercent accepts 0 (boundary β€” should it?)
+ it('should accept minFreeMemoryPercent of 0 in config.json (disable memory check)', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.resourceThresholds.minFreeMemoryPercent': 0,
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ // Kills: >= 0 β†’ > 0 mutant (zero is valid β€” disables memory gating)
+ expect(config.resourceThresholds.minFreeMemoryPercent).toBe(0);
+ });
+
+ // MUTANT: Remove `typeof ... === 'number'` check β†’ accept booleans
+ it('should reject boolean true as maxCpuLoad (typeof guard)', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.resourceThresholds.maxCpuLoad': true,
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ // Kills: removal of typeof check (true is truthy but not a number)
+ // JS: typeof true === 'boolean', not 'number'
+ expect(config.resourceThresholds.maxCpuLoad).not.toBe(true);
+ expect(typeof config.resourceThresholds.maxCpuLoad).toBe('number');
+ });
+
+ // MUTANT: State restore `rt.maxCpuLoad < 1000` β†’ remove upper bound
+ it('should reject absurdly large maxCpuLoad from saved state', () => {
+ const stateFile = join(tempDir, '.claude-flow', 'daemon-state.json');
+ writeFileSync(stateFile, JSON.stringify({
+ running: false,
+ workers: {},
+ config: {
+ resourceThresholds: { maxCpuLoad: 999999, minFreeMemoryPercent: 10 },
+ workers: [],
+ },
+ savedAt: new Date().toISOString(),
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ // Kills: removal of < 1000 bound in state restoration
+ expect(config.resourceThresholds.maxCpuLoad).toBeLessThan(1000);
+ });
+
+ // MUTANT: Swap CPU and memory checks in canRunWorker
+ it('should independently check CPU and memory (not conflate them)', async () => {
+ // High CPU + plenty of memory β†’ should block on CPU
+ const daemon1 = new WorkerDaemon(tempDir, {
+ resourceThresholds: { maxCpuLoad: 2.0, minFreeMemoryPercent: 5 },
+ });
+
+ vi.doMock('os', () => ({
+ default: {
+ loadavg: () => [10.0, 8.0, 6.0], // way over CPU
+ totalmem: () => 16e9,
+ freemem: () => 15e9, // 93% free β€” plenty of memory
+ },
+ loadavg: () => [10.0, 8.0, 6.0],
+ totalmem: () => 16e9,
+ freemem: () => 15e9,
+ }));
+
+ const result1 = await (daemon1 as any).canRunWorker();
+ expect(result1.allowed).toBe(false);
+ expect(result1.reason).toContain('CPU');
+ expect(result1.reason).not.toContain('emory'); // not memory
+
+ vi.doUnmock('os');
+
+ // Low CPU + low memory β†’ should block on memory
+ const tempDir2 = mkdtempSync(join(tmpdir(), 'worker-daemon-test-'));
+ mkdirSync(join(tempDir2, '.claude-flow', 'logs'), { recursive: true });
+ const daemon2 = new WorkerDaemon(tempDir2, {
+ resourceThresholds: { maxCpuLoad: 100, minFreeMemoryPercent: 50 },
+ });
+
+ vi.doMock('os', () => ({
+ default: {
+ loadavg: () => [0.1, 0.1, 0.1], // barely any CPU
+ totalmem: () => 16e9,
+ freemem: () => 1e9, // 6% free
+ },
+ loadavg: () => [0.1, 0.1, 0.1],
+ totalmem: () => 16e9,
+ freemem: () => 1e9,
+ }));
+
+ const result2 = await (daemon2 as any).canRunWorker();
+ expect(result2.allowed).toBe(false);
+ expect(result2.reason.toLowerCase()).toContain('memory');
+
+ rmSync(tempDir2, { recursive: true, force: true });
+ });
+
+ // MUTANT: Remove `config?.resourceThresholds?.maxCpuLoad` β†’ skip constructor arg
+ it('should use partial constructor resourceThresholds (only maxCpuLoad)', () => {
+ const daemon = new WorkerDaemon(tempDir, {
+ resourceThresholds: { maxCpuLoad: 77, minFreeMemoryPercent: 33 },
+ });
+ const config = daemon.getStatus().config;
+
+ // Kills: removal of config?.resourceThresholds?.maxCpuLoad path
+ expect(config.resourceThresholds.maxCpuLoad).toBe(77);
+ expect(config.resourceThresholds.minFreeMemoryPercent).toBe(33);
+ });
+
+ // MUTANT: readDaemonConfigFromFile returns {} even when file exists
+ it('should read maxConcurrent from config.json', () => {
+ const configFile = join(tempDir, '.claude-flow', 'config.json');
+ writeFileSync(configFile, JSON.stringify({
+ 'daemon.maxConcurrent': 8,
+ 'daemon.workerTimeoutMs': 120000,
+ }));
+
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ // Kills: return {} mutant in readDaemonConfigFromFile
+ expect(config.maxConcurrent).toBe(8);
+ expect(config.workerTimeoutMs).toBe(120000);
+ });
+
+ // MUTANT: Remove backoff timer value (30_000 β†’ 0)
+ it('should use 30s backoff delay, not 0', async () => {
+ const daemon = new WorkerDaemon(tempDir, {
+ maxConcurrent: 2,
+ resourceThresholds: { maxCpuLoad: 0.001, minFreeMemoryPercent: 99.99 },
+ });
+
+ (daemon as any).pendingWorkers.push('map');
+
+ const setTimeoutSpy = vi.spyOn(global, 'setTimeout');
+ const before = setTimeoutSpy.mock.calls.length;
+
+ await (daemon as any).processPendingWorkers();
+
+ const backoffCalls = setTimeoutSpy.mock.calls
+ .slice(before)
+ .filter((call) => call[1] === 30_000);
+ // Kills: 30_000 β†’ 0 mutant (must be exactly 30s)
+ expect(backoffCalls.length).toBe(1);
+ expect(backoffCalls[0][1]).toBe(30_000);
+
+ setTimeoutSpy.mockRestore();
+ });
+ });
+
+ // =========================================================================
+ // Container-aware CPU detection (WI-4)
+ // =========================================================================
+ describe('container-aware CPU detection', () => {
+ it('should expose getEffectiveCpuCount as a static method', () => {
+ expect(typeof WorkerDaemon.getEffectiveCpuCount).toBe('function');
+ });
+
+ it('should return a positive integer', () => {
+ const count = WorkerDaemon.getEffectiveCpuCount();
+ expect(count).toBeGreaterThanOrEqual(1);
+ expect(Number.isInteger(count)).toBe(true);
+ });
+
+ it('should match os.cpus().length on bare-metal (no cgroup quota)', () => {
+ // On a non-containerised host both cgroup reads will throw and the
+ // method falls back to os.cpus().length, so the two must agree.
+ const osCpuCount = cpus().length || 1;
+ const effectiveCount = WorkerDaemon.getEffectiveCpuCount();
+
+ // If we ARE inside a container with a quota the values may differ,
+ // so we only assert they are both positive β€” the equality check is
+ // a best-effort sanity test for bare-metal CI runners.
+ expect(effectiveCount).toBeGreaterThanOrEqual(1);
+ expect(effectiveCount).toBeLessThanOrEqual(osCpuCount);
+ });
+
+ it('should be used by the constructor for maxCpuLoad calculation', () => {
+ const daemon = new WorkerDaemon(tempDir);
+ const config = daemon.getStatus().config;
+
+ const effectiveCpus = WorkerDaemon.getEffectiveCpuCount();
+ const expectedMaxCpuLoad = Math.max(effectiveCpus * 0.8, 2.0);
+
+ expect(config.resourceThresholds.maxCpuLoad).toBeCloseTo(expectedMaxCpuLoad, 1);
+ });
+ });
+});
diff --git a/v3/@claude-flow/cli/src/commands/daemon.ts b/v3/@claude-flow/cli/src/commands/daemon.ts
index 691ea30978..a2303b332a 100644
--- a/v3/@claude-flow/cli/src/commands/daemon.ts
+++ b/v3/@claude-flow/cli/src/commands/daemon.ts
@@ -5,7 +5,7 @@
import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';
-import { WorkerDaemon, getDaemon, startDaemon, stopDaemon, type WorkerType } from '../services/worker-daemon.js';
+import { WorkerDaemon, getDaemon, startDaemon, stopDaemon, type WorkerType, type DaemonConfig } from '../services/worker-daemon.js';
import { spawn, execFile } from 'child_process';
import { fileURLToPath } from 'url';
import { dirname, join, resolve, isAbsolute } from 'path';
@@ -22,6 +22,8 @@ const startCommand: Command = {
{ name: 'foreground', short: 'f', type: 'boolean', description: 'Run daemon in foreground (blocks terminal)' },
{ name: 'headless', type: 'boolean', description: 'Enable headless worker execution (E2B sandbox)' },
{ name: 'sandbox', type: 'string', description: 'Default sandbox mode for headless workers', choices: ['strict', 'permissive', 'disabled'] },
+ { name: 'max-cpu-load', type: 'string', description: 'Override maxCpuLoad resource threshold (e.g. 4.0)' },
+ { name: 'min-free-memory', type: 'string', description: 'Override minFreeMemoryPercent resource threshold (e.g. 15)' },
],
examples: [
{ command: 'claude-flow daemon start', description: 'Start daemon in background (default)' },
@@ -35,6 +37,38 @@ const startCommand: Command = {
const projectRoot = process.cwd();
const isDaemonProcess = process.env.CLAUDE_FLOW_DAEMON === '1';
+ // Parse resource threshold overrides from CLI flags
+ const config: Partial<DaemonConfig> = {};
+ const rawMaxCpu = ctx.flags['max-cpu-load'] as string | undefined;
+ const rawMinMem = ctx.flags['min-free-memory'] as string | undefined;
+
+ // Strict numeric pattern to prevent command injection when forwarding to subprocess (S1)
+ const NUMERIC_RE = /^\d+(\.\d+)?$/;
+ const sanitize = (s: string) => s.replace(/[\x00-\x1f\x7f-\x9f]/g, '');
+
+ if (rawMaxCpu || rawMinMem) {
+ const thresholds: { maxCpuLoad?: number; minFreeMemoryPercent?: number } = {};
+ if (rawMaxCpu) {
+ const val = parseFloat(rawMaxCpu);
+ if (NUMERIC_RE.test(rawMaxCpu) && isFinite(val) && val > 0 && val <= 1000) {
+ thresholds.maxCpuLoad = val;
+ } else if (!quiet) {
+ output.printWarning(`Ignoring invalid --max-cpu-load value: ${sanitize(rawMaxCpu)}`);
+ }
+ }
+ if (rawMinMem) {
+ const val = parseFloat(rawMinMem);
+ if (NUMERIC_RE.test(rawMinMem) && isFinite(val) && val >= 0 && val <= 100) {
+ thresholds.minFreeMemoryPercent = val;
+ } else if (!quiet) {
+ output.printWarning(`Ignoring invalid --min-free-memory value: ${sanitize(rawMinMem)}`);
+ }
+ }
+ if (thresholds.maxCpuLoad !== undefined || thresholds.minFreeMemoryPercent !== undefined) {
+ config.resourceThresholds = thresholds as any;
+ }
+ }
+
// Check if background daemon already running (skip if we ARE the daemon process)
if (!isDaemonProcess) {
const bgPid = getBackgroundDaemonPid(projectRoot);
@@ -48,7 +82,7 @@ const startCommand: Command = {
// Background mode (default): fork a detached process
if (!foreground) {
- return startBackgroundDaemon(projectRoot, quiet);
+ return startBackgroundDaemon(projectRoot, quiet, rawMaxCpu, rawMinMem);
}
// Foreground mode: run in current process (blocks terminal)
@@ -84,7 +118,7 @@ const startCommand: Command = {
const spinner = output.createSpinner({ text: 'Starting worker daemon...', spinner: 'dots' });
spinner.start();
- const daemon = await startDaemon(projectRoot);
+ const daemon = await startDaemon(projectRoot, config);
const status = daemon.getStatus();
spinner.succeed('Worker daemon started (foreground mode)');
@@ -96,6 +130,8 @@ const startCommand: Command = {
`Started: ${status.startedAt?.toISOString()}`,
`Workers: ${status.config.workers.filter(w => w.enabled).length} enabled`,
`Max Concurrent: ${status.config.maxConcurrent}`,
+ `Max CPU Load: ${status.config.resourceThresholds.maxCpuLoad}`,
+ `Min Free Memory: ${status.config.resourceThresholds.minFreeMemoryPercent}%`,
].join('\n'),
'Daemon Status'
);
@@ -140,7 +176,7 @@ const startCommand: Command = {
// Keep process alive
await new Promise(() => {}); // Never resolves - daemon runs until killed
} else {
- await startDaemon(projectRoot);
+ await startDaemon(projectRoot, config);
await new Promise(() => {}); // Keep alive
}
@@ -182,7 +218,7 @@ function validatePath(path: string, label: string): void {
/**
* Start daemon as a detached background process
*/
-async function startBackgroundDaemon(projectRoot: string, quiet: boolean): Promise<CommandResult> {
+async function startBackgroundDaemon(projectRoot: string, quiet: boolean, maxCpuLoad?: string, minFreeMemory?: string): Promise<CommandResult> {
// Validate and resolve project root
const resolvedRoot = resolve(projectRoot);
validatePath(resolvedRoot, 'Project root');
@@ -231,10 +267,20 @@ async function startBackgroundDaemon(projectRoot: string, quiet: boolean): Promi
// Use spawn with explicit arguments instead of shell string interpolation
// This prevents command injection via paths
- const child = spawn(process.execPath, [
+ const spawnArgs = [
cliPath,
- 'daemon', 'start', '--foreground', '--quiet'
- ], spawnOpts);
+ 'daemon', 'start', '--foreground', '--quiet',
+ ];
+ // Forward resource threshold flags to the foreground child process
+ // Validate with strict numeric pattern to prevent shell injection on Windows (S1)
+ const SPAWN_NUMERIC_RE = /^\d+(\.\d+)?$/;
+ if (maxCpuLoad && SPAWN_NUMERIC_RE.test(maxCpuLoad)) {
+ spawnArgs.push('--max-cpu-load', maxCpuLoad);
+ }
+ if (minFreeMemory && SPAWN_NUMERIC_RE.test(minFreeMemory)) {
+ spawnArgs.push('--min-free-memory', minFreeMemory);
+ }
+ const child = spawn(process.execPath, spawnArgs, spawnOpts);
// Get PID from spawned process directly (no shell echo needed)
const pid = child.pid;
@@ -431,6 +477,8 @@ const statusCommand: Command = {
status.startedAt ? `Started: ${status.startedAt.toISOString()}` : '',
`Workers Enabled: ${status.config.workers.filter(w => w.enabled).length}`,
`Max Concurrent: ${status.config.maxConcurrent}`,
+ `Max CPU Load: ${status.config.resourceThresholds.maxCpuLoad}`,
+ `Min Free Memory: ${status.config.resourceThresholds.minFreeMemoryPercent}%`,
].filter(Boolean).join('\n'),
'RuFlo Daemon'
);
diff --git a/v3/@claude-flow/cli/src/services/index.ts b/v3/@claude-flow/cli/src/services/index.ts
index af630529c5..80767777e4 100644
--- a/v3/@claude-flow/cli/src/services/index.ts
+++ b/v3/@claude-flow/cli/src/services/index.ts
@@ -58,7 +58,7 @@ export {
} from './worker-queue.js';
// Re-export types
-export type { default as WorkerDaemonType } from './worker-daemon.js';
+export type { default as WorkerDaemonType, DaemonConfig } from './worker-daemon.js';
export type { default as HeadlessWorkerExecutorType } from './headless-worker-executor.js';
export type { default as ContainerWorkerPoolType } from './container-worker-pool.js';
export type { default as WorkerQueueType } from './worker-queue.js';
diff --git a/v3/@claude-flow/cli/src/services/worker-daemon.ts b/v3/@claude-flow/cli/src/services/worker-daemon.ts
index 25ac71fa54..05a68e008d 100644
--- a/v3/@claude-flow/cli/src/services/worker-daemon.ts
+++ b/v3/@claude-flow/cli/src/services/worker-daemon.ts
@@ -12,6 +12,7 @@
import { EventEmitter } from 'events';
import { existsSync, mkdirSync, writeFileSync, readFileSync, appendFileSync } from 'fs';
+import { cpus } from 'os';
import { join } from 'path';
import {
HeadlessWorkerExecutor,
@@ -73,7 +74,7 @@ interface DaemonStatus {
config: DaemonConfig;
}
-interface DaemonConfig {
+export interface DaemonConfig {
autoStart: boolean;
logDir: string;
stateFile: string;
@@ -122,21 +123,41 @@ export class WorkerDaemon extends EventEmitter {
private headlessExecutor: HeadlessWorkerExecutor | null = null;
private headlessAvailable: boolean = false;
+ // Preserve the original constructor config so we can detect explicit overrides
+ // during state restoration (R1: constructor config takes priority over stale state)
+ private originalConfig?: Partial<DaemonConfig>;
+
constructor(projectRoot: string, config?: Partial<DaemonConfig>) {
super();
this.projectRoot = projectRoot;
+ this.originalConfig = config;
const claudeFlowDir = join(projectRoot, '.claude-flow');
+ // Read daemon config from .claude-flow/config.json (Layer B)
+ const fileConfig = this.readDaemonConfigFromFile(claudeFlowDir);
+
+ // CPU-proportional smart default instead of hardcoded 2.0
+ const cpuCount = WorkerDaemon.getEffectiveCpuCount();
+ const smartMaxCpuLoad = Math.max(cpuCount * 0.8, 2.0); // Floor of 2.0 for single-CPU machines
+
+ // Platform-aware default: macOS os.freemem() excludes reclaimable file cache,
+ // so reported "free" is much lower than actually available memory.
+ // Linux reports available memory (including reclaimable cache) more accurately.
+ const defaultMinFreeMemory = process.platform === 'darwin' ? 5 : 10;
+
+ // Priority: constructor arg > config.json > smart default
+ // For resourceThresholds, merge field-by-field so partial overrides
+ // (e.g. only --max-cpu-load) still pick up defaults for other fields.
this.config = {
- autoStart: config?.autoStart ?? false, // P1 fix: Default to false for explicit consent
+ autoStart: config?.autoStart ?? fileConfig.autoStart ?? false,
logDir: config?.logDir ?? join(claudeFlowDir, 'logs'),
stateFile: config?.stateFile ?? join(claudeFlowDir, 'daemon-state.json'),
- maxConcurrent: config?.maxConcurrent ?? 2, // P0 fix: Limit concurrent workers
- workerTimeoutMs: config?.workerTimeoutMs ?? DEFAULT_WORKER_TIMEOUT_MS,
- resourceThresholds: config?.resourceThresholds ?? {
- maxCpuLoad: 2.0,
- minFreeMemoryPercent: 20,
+ maxConcurrent: config?.maxConcurrent ?? fileConfig.maxConcurrent ?? 2,
+ workerTimeoutMs: config?.workerTimeoutMs ?? fileConfig.workerTimeoutMs ?? DEFAULT_WORKER_TIMEOUT_MS,
+ resourceThresholds: {
+ maxCpuLoad: config?.resourceThresholds?.maxCpuLoad ?? fileConfig.maxCpuLoad ?? smartMaxCpuLoad,
+ minFreeMemoryPercent: config?.resourceThresholds?.minFreeMemoryPercent ?? fileConfig.minFreeMemoryPercent ?? defaultMinFreeMemory,
},
workers: config?.workers ?? DEFAULT_WORKERS,
};
@@ -214,6 +235,70 @@ export class WorkerDaemon extends EventEmitter {
return this.headlessExecutor;
}
+ /**
+ * Detect effective CPU count for the current environment.
+ *
+ * Inside Docker / K8s containers, os.cpus().length reports the HOST cpu
+ * count, not the container limit (Node.js #28762 β€” wontfix). We read
+ * cgroup v2 / v1 quota files first so the maxCpuLoad threshold stays
+ * meaningful under resource-limited containers.
+ */
+ static getEffectiveCpuCount(): number {
+ // 1. Try cgroup v2: /sys/fs/cgroup/cpu.max
+ try {
+ const cpuMax = readFileSync('/sys/fs/cgroup/cpu.max', 'utf8').trim();
+ const [quotaStr, periodStr] = cpuMax.split(' ');
+ if (quotaStr !== 'max') {
+ const quota = parseInt(quotaStr, 10);
+ const period = parseInt(periodStr, 10);
+ if (quota > 0 && period > 0) return Math.ceil(quota / period);
+ }
+ } catch { /* not in cgroup v2 */ }
+
+ // 2. Try cgroup v1: /sys/fs/cgroup/cpu/cpu.cfs_quota_us
+ try {
+ const quota = parseInt(readFileSync('/sys/fs/cgroup/cpu/cpu.cfs_quota_us', 'utf8').trim(), 10);
+ const period = parseInt(readFileSync('/sys/fs/cgroup/cpu/cpu.cfs_period_us', 'utf8').trim(), 10);
+ if (quota > 0 && period > 0) return Math.ceil(quota / period);
+ } catch { /* not in cgroup v1 */ }
+
+ // 3. Fallback to os.cpus().length
+ return cpus().length || 1;
+ }
+
+ /**
+ * Read daemon-specific config from .claude-flow/config.json
+ * Supports dot-notation keys like 'daemon.resourceThresholds.maxCpuLoad'
+ */
+ private readDaemonConfigFromFile(claudeFlowDir: string): {
+ autoStart?: boolean;
+ maxConcurrent?: number;
+ workerTimeoutMs?: number;
+ maxCpuLoad?: number;
+ minFreeMemoryPercent?: number;
+ } {
+ const configPath = join(claudeFlowDir, 'config.json');
+ if (!existsSync(configPath)) return {};
+ try {
+ const raw = JSON.parse(readFileSync(configPath, 'utf-8'));
+ // Support both flat keys at root and nested under scopes.project
+ const cfg = raw?.scopes?.project ?? raw;
+ const rawCpuLoad = cfg['daemon.resourceThresholds.maxCpuLoad'] ?? raw['daemon.resourceThresholds.maxCpuLoad'];
+ const rawMinMem = cfg['daemon.resourceThresholds.minFreeMemoryPercent'] ?? raw['daemon.resourceThresholds.minFreeMemoryPercent'];
+ const rawMaxConcurrent = cfg['daemon.maxConcurrent'] ?? raw['daemon.maxConcurrent'];
+ const rawTimeout = cfg['daemon.workerTimeoutMs'] ?? raw['daemon.workerTimeoutMs'];
+ return {
+ autoStart: typeof raw['daemon.autoStart'] === 'boolean' ? raw['daemon.autoStart'] : undefined,
+ maxConcurrent: (typeof rawMaxConcurrent === 'number' && rawMaxConcurrent > 0) ? rawMaxConcurrent : undefined,
+ workerTimeoutMs: (typeof rawTimeout === 'number' && rawTimeout > 0) ? rawTimeout : undefined,
+ maxCpuLoad: (typeof rawCpuLoad === 'number' && rawCpuLoad > 0 && rawCpuLoad < 1000) ? rawCpuLoad : undefined,
+ minFreeMemoryPercent: (typeof rawMinMem === 'number' && rawMinMem >= 0 && rawMinMem <= 100) ? rawMinMem : undefined,
+ };
+ } catch {
+ return {};
+ }
+ }
+
/**
* Setup graceful shutdown handlers
*/
@@ -250,13 +335,30 @@ export class WorkerDaemon extends EventEmitter {
/**
* Process pending workers queue
+ *
+ * When executeWorkerWithConcurrencyControl defers a worker (returns null),
+ * we break immediately to avoid a busy-wait loop β€” the deferred worker is
+ * already back on the pendingWorkers queue by that point. If no workers are
+ * currently running when we break, we schedule a backoff retry so the queue
+ * does not get permanently stuck.
*/
private async processPendingWorkers(): Promise<void> {
while (this.pendingWorkers.length > 0 && this.runningWorkers.size < this.config.maxConcurrent) {
const workerType = this.pendingWorkers.shift()!;
const workerConfig = this.config.workers.find(w => w.type === workerType);
if (workerConfig) {
- await this.executeWorkerWithConcurrencyControl(workerConfig);
+ const result = await this.executeWorkerWithConcurrencyControl(workerConfig);
+ if (result === null) {
+ // Worker was deferred (resource pressure or concurrency limit).
+ // Break to avoid tight-looping β€” the next executeWorker() completion
+ // will call processPendingWorkers() again via the finally block.
+ if (this.runningWorkers.size === 0) {
+ // No workers running means nobody will trigger the finally-block
+ // callback, so schedule a backoff retry to avoid a stuck queue.
+ setTimeout(() => this.processPendingWorkers(), 30_000).unref();
+ }
+ break;
+ }
}
}
}
@@ -278,6 +380,24 @@ export class WorkerDaemon extends EventEmitter {
}
}
+ // Restore resourceThresholds, maxConcurrent, workerTimeoutMs from saved state
+ // Only restore if valid numeric values within sane ranges
+ if (saved.config?.resourceThresholds && !this.originalConfig?.resourceThresholds) {
+ const rt = saved.config.resourceThresholds;
+ if (typeof rt.maxCpuLoad === 'number' && rt.maxCpuLoad > 0 && rt.maxCpuLoad < 1000) {
+ this.config.resourceThresholds.maxCpuLoad = rt.maxCpuLoad;
+ }
+ if (typeof rt.minFreeMemoryPercent === 'number' && rt.minFreeMemoryPercent >= 0 && rt.minFreeMemoryPercent <= 100) {
+ this.config.resourceThresholds.minFreeMemoryPercent = rt.minFreeMemoryPercent;
+ }
+ }
+ if (typeof saved.config?.maxConcurrent === 'number' && saved.config.maxConcurrent > 0) {
+ this.config.maxConcurrent = saved.config.maxConcurrent;
+ }
+ if (typeof saved.config?.workerTimeoutMs === 'number' && saved.config.workerTimeoutMs > 0) {
+ this.config.workerTimeoutMs = saved.config.workerTimeoutMs;
+ }
+
// Restore worker runtime states (runCount, successCount, etc.)
if (saved.workers) {
for (const [type, state] of Object.entries(saved.workers)) {
@@ -336,7 +456,7 @@ export class WorkerDaemon extends EventEmitter {
// Save state
this.saveState();
- this.log('info', `Daemon started with ${this.config.workers.filter(w => w.enabled).length} workers`);
+ this.log('info', `Daemon started (PID: ${process.pid}, CPUs: ${cpus().length}, workers: ${this.config.workers.filter(w => w.enabled).length}, maxCpuLoad: ${this.config.resourceThresholds.maxCpuLoad}, minFreeMemoryPercent: ${this.config.resourceThresholds.minFreeMemoryPercent}%)`);
}
/**
@@ -937,9 +1057,9 @@ let daemonInstance: WorkerDaemon | null = null;
/**
* Get or create daemon instance
*/
-export function getDaemon(projectRoot?: string): WorkerDaemon {
+export function getDaemon(projectRoot?: string, config?: Partial<DaemonConfig>): WorkerDaemon {
if (!daemonInstance && projectRoot) {
- daemonInstance = new WorkerDaemon(projectRoot);
+ daemonInstance = new WorkerDaemon(projectRoot, config);
}
if (!daemonInstance) {
throw new Error('Daemon not initialized. Provide projectRoot on first call.');
@@ -950,8 +1070,8 @@ export function getDaemon(projectRoot?: string): WorkerDaemon {
/**
* Start daemon (for use in session-start hook)
*/
-export async function startDaemon(projectRoot: string): Promise<WorkerDaemon> {
- const daemon = getDaemon(projectRoot);
+export async function startDaemon(projectRoot: string, config?: Partial<DaemonConfig>): Promise<WorkerDaemon> {
+ const daemon = getDaemon(projectRoot, config);
await daemon.start();
return daemon;
}