π 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(daemon): config.json resourceThresholds overrides were lost to stale daemon-state.json (#2935) (#3000)
rUv35a6ad369760
diff --git a/v3/@claude-flow/cli/__tests__/daemon-config-restore-staleness-2935.test.ts b/v3/@claude-flow/cli/__tests__/daemon-config-restore-staleness-2935.test.tsnew file mode 100644index 0000000000..256612d3cf--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/daemon-config-restore-staleness-2935.test.ts@@ -0,0 +1,117 @@+/**+ * Regression guard for ruvnet/ruflo#2935.+ *+ * A resourceThresholds value set explicitly in .claude-flow/config.json is+ * just as much a deliberate override as a constructor arg β but+ * initializeWorkerStates()'s stale-state restoration guard only ever+ * checked the constructor arg (`originalConfig`), so a config.json override+ * (e.g. working around the Darwin os.freemem() skew with+ * `minFreeMemoryPercent: 0`) silently lost to whatever a stale+ * .claude-flow/daemon-state.json had persisted from a previous run. Same+ * bug class as #2661 (aiWorkersEnabled), fixed the same way: exclude the+ * field from restoration once an explicit source (constructor OR file) set+ * it.+ *+ * Also covers #2935's secondary diagnostic bug: readDaemonConfigFromFile()+ * used to log "Daemon config loaded from ..." via this.log() while running+ * from the constructor BEFORE this.config exists, so the log() call threw+ * inside its own try/catch and the line never reached daemon.log.+ */+import { describe, it, expect, afterEach } from 'vitest';+import { WorkerDaemon } from '../src/services/worker-daemon.js';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';+import { join } from 'path';+import { tmpdir } from 'os';++describe('#2935 β config.json resourceThresholds override survives a stale daemon-state.json', () => {+ let tempDir: string;++ afterEach(() => {+ rmSync(tempDir, { recursive: true, force: true });+ process.removeAllListeners('SIGTERM');+ process.removeAllListeners('SIGINT');+ process.removeAllListeners('SIGHUP');+ });++ function setup(): string {+ tempDir = mkdtempSync(join(tmpdir(), 'daemon-2935-test-'));+ mkdirSync(join(tempDir, '.claude-flow', 'logs'), { recursive: true });+ return tempDir;+ }++ it('a config.json minFreeMemoryPercent override is NOT overwritten by stale daemon-state.json', () => {+ const dir = setup();+ writeFileSync(+ join(dir, '.claude-flow', 'config.json'),+ JSON.stringify({ 'daemon.resourceThresholds.minFreeMemoryPercent': 0 }),+ );+ // Simulate a daemon-state.json persisted by an earlier run BEFORE the+ // override existed β this is exactly the reporter's 13-day-stale case.+ writeFileSync(+ join(dir, '.claude-flow', 'daemon-state.json'),+ JSON.stringify({+ running: false,+ config: { resourceThresholds: { maxCpuLoad: 8, minFreeMemoryPercent: 5 } },+ workers: {},+ }),+ );++ const daemon = new WorkerDaemon(dir);+ expect(daemon.getStatus().config.resourceThresholds.minFreeMemoryPercent).toBe(0);+ });++ it('a maxCpuLoad NOT set in config.json can still restore from daemon-state.json (per-field granularity)', () => {+ const dir = setup();+ writeFileSync(+ join(dir, '.claude-flow', 'config.json'),+ JSON.stringify({ 'daemon.resourceThresholds.minFreeMemoryPercent': 0 }),+ );+ writeFileSync(+ join(dir, '.claude-flow', 'daemon-state.json'),+ JSON.stringify({+ running: false,+ config: { resourceThresholds: { maxCpuLoad: 8, minFreeMemoryPercent: 5 } },+ workers: {},+ }),+ );++ const daemon = new WorkerDaemon(dir);+ const rt = daemon.getStatus().config.resourceThresholds;+ // minFreeMemoryPercent: file override wins (0, not the stale 5).+ expect(rt.minFreeMemoryPercent).toBe(0);+ // maxCpuLoad: no explicit source set it, so restoring the saved value+ // is still correct behavior β unlike an all-or-nothing gate, this field+ // isn't collateral damage from the other field's override.+ expect(rt.maxCpuLoad).toBe(8);+ });++ it('constructor arg for resourceThresholds still beats stale daemon-state.json (existing #originalConfig behavior)', () => {+ const dir = setup();+ writeFileSync(+ join(dir, '.claude-flow', 'daemon-state.json'),+ JSON.stringify({+ running: false,+ config: { resourceThresholds: { maxCpuLoad: 8, minFreeMemoryPercent: 5 } },+ workers: {},+ }),+ );++ const daemon = new WorkerDaemon(dir, { resourceThresholds: { maxCpuLoad: 3, minFreeMemoryPercent: 1 } });+ const rt = daemon.getStatus().config.resourceThresholds;+ expect(rt.maxCpuLoad).toBe(3);+ expect(rt.minFreeMemoryPercent).toBe(1);+ });++ it('logs "Daemon config loaded from" to daemon.log once this.config exists (was silently swallowed)', () => {+ const dir = setup();+ writeFileSync(+ join(dir, '.claude-flow', 'config.json'),+ JSON.stringify({ 'daemon.resourceThresholds.minFreeMemoryPercent': 0 }),+ );++ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ const daemon = new WorkerDaemon(dir);+ const logContent = readFileSync(join(dir, '.claude-flow', 'logs', 'daemon.log'), 'utf-8');+ expect(logContent).toMatch(/Daemon config loaded from .*config\.json/);+ });+});diff --git a/v3/@claude-flow/cli/src/services/worker-daemon.ts b/v3/@claude-flow/cli/src/services/worker-daemon.tsindex 7ff6d52bc4..a4c163d315 100644--- a/v3/@claude-flow/cli/src/services/worker-daemon.ts+++ b/v3/@claude-flow/cli/src/services/worker-daemon.ts@@ -235,6 +235,15 @@ export class WorkerDaemon extends EventEmitter {// during state restoration (R1: constructor config takes priority over stale state)private originalConfig?: Partial<DaemonConfig>;+ // #2935 β same purpose as originalConfig, but for values that came from+ // .claude-flow/config.{json,yaml,yml} (Layer B) rather than a constructor+ // arg. A file-supplied resourceThresholds value is just as much an+ // explicit, deliberate override as a constructor arg, but+ // initializeWorkerStates()'s stale-state guard only ever checked+ // originalConfig β so a config.json override kept losing to whatever+ // .claude-flow/daemon-state.json had persisted from a previous run.+ private fileConfigResourceThresholds?: { maxCpuLoad?: number; minFreeMemoryPercent?: number };+// #2661 root-fix β resolved once (git identity doesn't change at runtime)// and reused for lease heartbeats + supervisor election, both gated on// aiWorkersEnabled since they only matter for the recurring AI schedule.@@ -250,6 +259,12 @@ export class WorkerDaemon extends EventEmitter {// Read daemon config from .claude-flow/config.json (Layer B)const fileConfig = this.readDaemonConfigFromFile(claudeFlowDir);+ // #2935 β remember which resourceThresholds fields came from the file so+ // initializeWorkerStates() can treat them as explicit too (see field doc).+ this.fileConfigResourceThresholds = {+ maxCpuLoad: fileConfig.maxCpuLoad,+ minFreeMemoryPercent: fileConfig.minFreeMemoryPercent,+ };// CPU-proportional smart default instead of hardcoded 2.0const cpuCount = WorkerDaemon.getEffectiveCpuCount();@@ -299,6 +314,17 @@ export class WorkerDaemon extends EventEmitter {workers: config?.workers ?? DEFAULT_WORKERS,};+ // #2935 β deferred from readDaemonConfigFromFile(): this.config (and+ // therefore this.config.logDir) doesn't exist until the assignment+ // above, so logging from inside that method was silently swallowed by+ // log()'s own try/catch and never reached daemon.log.+ if (fileConfig.configSourcePath) {+ this.log('info', `Daemon config loaded from ${fileConfig.configSourcePath}`);+ }+ if (fileConfig.yamlParseWarning) {+ this.log('warn', fileConfig.yamlParseWarning);+ }+// Setup graceful shutdown handlersthis.setupShutdownHandlers();@@ -451,7 +477,13 @@ export class WorkerDaemon extends EventEmitter {* Supports dot-notation keys like 'daemon.resourceThresholds.maxCpuLoad'.* #1844: prefer JSON when both exist (existing behavior) but fall back* to YAML so operators using the v3 canonical YAML format aren't silently- * ignored. The chosen path is logged at info level.+ * ignored. The chosen path (or a parse warning) is returned rather than+ * logged directly β #2935: this method runs from the constructor before+ * `this.config` (and therefore `this.config.logDir`) is assigned, so a+ * `this.log()` call made here throws inside log()'s own try/catch and is+ * silently swallowed. It never reached daemon.log, which made "is the+ * config file even being read?" impossible to answer from the log alone.+ * The caller logs these once `this.config` exists.*/private readDaemonConfigFromFile(claudeFlowDir: string): {autoStart?: boolean;@@ -462,6 +494,8 @@ export class WorkerDaemon extends EventEmitter {ttlMs?: number;idleShutdownMs?: number;aiWorkersEnabled?: boolean;+ configSourcePath?: string;+ yamlParseWarning?: string;} {const jsonPath = join(claudeFlowDir, 'config.json');const yamlPath = join(claudeFlowDir, 'config.yaml');@@ -492,18 +526,15 @@ export class WorkerDaemon extends EventEmitter {chosenPath = yPath;}} catch {- this.log(- 'warn',- `Found ${yPath} but yaml parser unavailable. Install \`yaml\` or convert to JSON. Falling back to defaults.`,- );- return {};+ return {+ yamlParseWarning: `Found ${yPath} but yaml parser unavailable. Install \`yaml\` or convert to JSON. Falling back to defaults.`,+ };}}if (!raw || !chosenPath) {return {};}- this.log('info', `Daemon config loaded from ${chosenPath}`);try {// Support both flat keys at root and nested under scopes.project@@ -528,6 +559,7 @@ export class WorkerDaemon extends EventEmitter {ttlMs: (typeof rawTtl === 'number' && rawTtl >= 0) ? rawTtl * 1000 : undefined,idleShutdownMs: (typeof rawIdle === 'number' && rawIdle >= 0) ? rawIdle * 1000 : undefined,aiWorkersEnabled: typeof rawAiEnabled === 'boolean' ? rawAiEnabled : undefined,+ configSourcePath: chosenPath,};} catch {return {};@@ -759,13 +791,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) {+ // Only restore if valid numeric values within sane ranges.+ // #2935 β a field is restored from stale state only if NEITHER the+ // constructor arg NOR .claude-flow/config.{json,yaml,yml} explicitly+ // set it. The old gate checked only `originalConfig`, so a+ // config.json override (e.g. minFreeMemoryPercent: 0 to work around+ // the Darwin os.freemem() skew) silently lost to whatever a stale+ // daemon-state.json had persisted from before the override existed β+ // same class of bug #2661 already fixed for aiWorkersEnabled.+ if (saved.config?.resourceThresholds) {const rt = saved.config.resourceThresholds;- if (typeof rt.maxCpuLoad === 'number' && rt.maxCpuLoad > 0 && rt.maxCpuLoad < 1000) {+ const maxCpuLoadExplicit = this.originalConfig?.resourceThresholds?.maxCpuLoad !== undefined+ || this.fileConfigResourceThresholds?.maxCpuLoad !== undefined;+ const minFreeMemExplicit = this.originalConfig?.resourceThresholds?.minFreeMemoryPercent !== undefined+ || this.fileConfigResourceThresholds?.minFreeMemoryPercent !== undefined;+ if (!maxCpuLoadExplicit && 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) {+ if (!minFreeMemExplicit && typeof rt.minFreeMemoryPercent === 'number' && rt.minFreeMemoryPercent >= 0 && rt.minFreeMemoryPercent <= 100) {this.config.resourceThresholds.minFreeMemoryPercent = rt.minFreeMemoryPercent;}}