diff --git a/tests/config-numeric-scalars.test.mjs b/tests/config-numeric-scalars.test.mjs new file mode 100644 index 0000000000..dcc3afefb2 --- /dev/null +++ b/tests/config-numeric-scalars.test.mjs @@ -0,0 +1,10 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { parseConfigValue } from '../v3/@claude-flow/cli/src/services/config-file-manager.ts'; +test('numeric configuration values preserve JSON number semantics', () => { + for (const value of ['-1', '-0.5', '1e3', '1E-3', ' 42 ']) assert.equal(parseConfigValue(value), JSON.parse(value)); +}); +test('non-numeric strings and existing structured scalars retain their semantics', () => { + for (const value of ['auto', 'Infinity', 'NaN', 'host']) assert.equal(parseConfigValue(value), value); + assert.deepEqual(parseConfigValue('[1,2]'), [1,2]); assert.equal(parseConfigValue('false'), false); assert.equal(parseConfigValue('123'), 123); +}); diff --git a/tests/config-write-rollback.test.mjs b/tests/config-write-rollback.test.mjs new file mode 100644 index 0000000000..4decb76a4f --- /dev/null +++ b/tests/config-write-rollback.test.mjs @@ -0,0 +1,16 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { mkdtempSync, writeFileSync, rmSync, mkdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { ConfigFileManager } from '../v3/@claude-flow/cli/src/services/config-file-manager.ts'; +test('failed atomic replacement leaves cached configuration unchanged', () => { + const root = mkdtempSync(join(tmpdir(), 'config-rollback-')); const file = join(root, 'claude-flow.config.json'); + try { + writeFileSync(file, JSON.stringify({ agents: { maxConcurrent: 2 } })); const m = new ConfigFileManager(); m.load(root); + rmSync(file); mkdirSync(file); + assert.throws(() => m.set(root, 'agents.maxConcurrent', 9)); + assert.equal(m.get(root, 'agents.maxConcurrent'), 2); + rmSync(file, { recursive: true }); m.set(root, 'agents.maxConcurrent', 3); assert.equal(JSON.parse(readFileSync(file, 'utf8')).agents.maxConcurrent, 3); + } finally { rmSync(root, { recursive: true, force: true }); } +}); diff --git a/tests/monitor-alert-escalation.test.mjs b/tests/monitor-alert-escalation.test.mjs new file mode 100644 index 0000000000..c498436cda --- /dev/null +++ b/tests/monitor-alert-escalation.test.mjs @@ -0,0 +1,13 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { MonitoringHooks } from '../v3/@claude-flow/cli/src/production/monitoring.ts'; +test('critical readings escalate an existing warning instead of being suppressed', () => { + const m = new MonitoringHooks({ alertThresholds: { load: { warning: 10, critical: 20 } } }); + m.gauge('load', 11); const id = m.getAlerts()[0].id; + m.gauge('load', 25); + const alerts = m.getAlerts(); assert.equal(alerts.length, 1); assert.equal(alerts[0].id, id); assert.equal(alerts[0].level, 'critical'); assert.equal(alerts[0].value, 25); assert.equal(alerts[0].threshold, 20); assert.match(alerts[0].message, /critical/); + m.gauge('load', 12); assert.equal(m.getAlerts()[0].level, 'critical'); +}); +test('repeated warning readings stay deduplicated', () => { + const m = new MonitoringHooks({ alertThresholds: { load: { warning: 10, critical: 20 } } }); m.gauge('load', 11); m.gauge('load', 12); assert.equal(m.getAlerts().length, 1); +}); diff --git a/tests/monitor-export-snapshots.test.mjs b/tests/monitor-export-snapshots.test.mjs new file mode 100644 index 0000000000..7f26d1b16b --- /dev/null +++ b/tests/monitor-export-snapshots.test.mjs @@ -0,0 +1,12 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { MonitoringHooks } from '../v3/@claude-flow/cli/src/production/monitoring.ts'; +test('exported metrics do not alias stored values or labels', () => { + const m = new MonitoringHooks(); m.counter('read', 1, { route: 'original' }); const row = m.getMetrics('read')[0]; row.value = 999; row.labels.route = 'changed'; assert.equal(m.getMetrics('read')[0].value, 1); assert.equal(m.getMetrics('read')[0].labels.route, 'original'); +}); +test('exported alerts do not acknowledge live alerts through mutation', () => { + const m = new MonitoringHooks({ alertThresholds: { load: { warning: 1, critical: 2 } } }); m.gauge('load', 3); const alert = m.getAlerts()[0]; alert.acknowledged = true; assert.equal(m.getAlerts().length, 1); assert.equal(m.acknowledgeAlert(alert.id), true); assert.equal(m.getAlerts().length, 0); +}); +test('health status results do not alias live checks', async () => { + const m = new MonitoringHooks(); m.registerHealthCheck('db', async () => ({ healthy: true })); const result = await m.runHealthChecks(); result.checks.db.status = 'unhealthy'; const status = m.getHealthStatus(); assert.equal(status.checks.db.status, 'healthy'); status.checks.db.message = 'changed'; assert.equal(m.getHealthStatus().checks.db.message, undefined); +}); diff --git a/tests/monitor-health-rejections.test.mjs b/tests/monitor-health-rejections.test.mjs new file mode 100644 index 0000000000..5e0c078b01 --- /dev/null +++ b/tests/monitor-health-rejections.test.mjs @@ -0,0 +1,16 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { MonitoringHooks } from '../v3/@claude-flow/cli/src/production/monitoring.ts'; +test('non-Error health failures are recorded without aborting later checks', async () => { + const m = new MonitoringHooks(); + for (const [name, value] of [['null', null], ['undefined', undefined], ['string', 'offline']]) m.registerHealthCheck(name, async () => { throw value; }); + m.registerHealthCheck('healthy', async () => ({ healthy: true })); + const result = await m.runHealthChecks(); + assert.equal(result.healthy, false); + for (const [name, value] of [['null', null], ['undefined', undefined], ['string', 'offline']]) { assert.equal(result.checks[name].status, 'unhealthy'); assert.equal(result.checks[name].message, String(value)); } + assert.equal(result.checks.healthy.status, 'healthy'); +}); +test('Error rejection retains the original message', async () => { + const m = new MonitoringHooks(); m.registerHealthCheck('error', async () => { throw new Error('unavailable'); }); + assert.equal((await m.runHealthChecks()).checks.error.message, 'unavailable'); +}); diff --git a/tests/monitor-request-completion.test.mjs b/tests/monitor-request-completion.test.mjs new file mode 100644 index 0000000000..3c4a43f2f2 --- /dev/null +++ b/tests/monitor-request-completion.test.mjs @@ -0,0 +1,14 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { MonitoringHooks } from '../v3/@claude-flow/cli/src/production/monitoring.ts'; +test('request completion is idempotent', () => { + const m = new MonitoringHooks(); const end = m.startRequest('one'); end(); end(); + assert.equal(m.getPerformanceMetrics().activeRequests, 0); + assert.equal(m.getMetrics('response_time_ms').length, 1); +}); +test('completion from before reset cannot corrupt the new monitoring interval', () => { + const m = new MonitoringHooks(); const oldEnd = m.startRequest('old'); m.reset(); const end = m.startRequest('new'); oldEnd(); + assert.equal(m.getPerformanceMetrics().activeRequests, 1); + assert.equal(m.getMetrics('response_time_ms').length, 0); + end(); assert.equal(m.getPerformanceMetrics().activeRequests, 0); +}); diff --git a/tests/parser-array-defaults.test.mjs b/tests/parser-array-defaults.test.mjs new file mode 100644 index 0000000000..d7436d55e3 --- /dev/null +++ b/tests/parser-array-defaults.test.mjs @@ -0,0 +1,10 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { CommandParser } from '../v3/@claude-flow/cli/src/parser.ts'; +test('command array defaults are independent across parses', () => { + const defaults = ['base']; const p = new CommandParser(); p.registerCommand({ name: 'root', description: '', options: [{ name: 'models', description: '', type: 'array', default: defaults }] }); + p.parse(['root']).flags.models.push('injected'); assert.deepEqual(p.parse(['root']).flags.models, ['base']); assert.deepEqual(defaults, ['base']); +}); +test('custom array defaults are independent across parses', () => { + const defaults = ['base']; const p = new CommandParser({ defaults: { models: defaults } }); p.parse([]).flags.models.push('injected'); assert.deepEqual(p.parse([]).flags.models, ['base']); assert.deepEqual(defaults, ['base']); +}); diff --git a/tests/parser-array-options.test.mjs b/tests/parser-array-options.test.mjs new file mode 100644 index 0000000000..fc3e5ae5ce --- /dev/null +++ b/tests/parser-array-options.test.mjs @@ -0,0 +1,15 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { CommandParser } from '../v3/@claude-flow/cli/src/parser.ts'; +const command = { name: 'build', description: '', options: [{ name: 'models', short: 'm', description: '', type: 'array' }] }; +test('declared array options produce arrays across long, short and repeated forms', () => { + const p = new CommandParser(); p.registerCommand(command); + for (const args of [['build', '--models', 'model-a'], ['build', '-m', 'model-a'], ['build', '--models=model-a']]) assert.equal(p.parse(args).flags.models.join(', '), 'model-a'); + assert.deepEqual(p.parse(['build', '--models=007', '-m', 'false']).flags.models, ['007', 'false']); +}); +test('custom array flags preserve text and accumulate values', () => { + const p = new CommandParser({ arrayFlags: ['model-ids'] }); assert.deepEqual(p.parse(['--model-ids=007', '--model-ids=true']).flags.modelIds, ['007', 'true']); +}); +test('array options without a value are rejected', () => { + const p = new CommandParser(); p.registerCommand(command); assert.match(p.validateFlags(p.parse(['build', '--models']).flags, command).join(' '), /needs a value/); +}); diff --git a/tests/parser-command-slot.test.mjs b/tests/parser-command-slot.test.mjs new file mode 100644 index 0000000000..3d535dd4c6 --- /dev/null +++ b/tests/parser-command-slot.test.mjs @@ -0,0 +1,19 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { CommandParser } from '../v3/@claude-flow/cli/src/parser.ts'; +const parser = () => { const p = new CommandParser(); p.registerCommand({ name: 'memory', description: 'Memory', action() {} }); return p; }; +test('unknown command slot is not replaced by later command names', () => { + const result = parser().parse(['unknown', 'memory']); + assert.deepEqual(result.command, []); + assert.deepEqual(result.positional, ['unknown', 'memory']); +}); +test('end-of-options arguments remain literal positionals', () => { + const result = parser().parse(['--', 'memory']); + assert.deepEqual(result.command, []); + assert.deepEqual(result.positional, ['memory']); +}); +test('leading flag values do not occupy the command slot', () => { + const result = parser().parse(['--config', 'memory', 'memory']); + assert.deepEqual(result.command, ['memory']); + assert.equal(result.flags.config, 'memory'); +}); diff --git a/tests/parser-nested-defaults.test.mjs b/tests/parser-nested-defaults.test.mjs new file mode 100644 index 0000000000..0e20f409d3 --- /dev/null +++ b/tests/parser-nested-defaults.test.mjs @@ -0,0 +1,12 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { CommandParser } from '../v3/@claude-flow/cli/src/parser.ts'; +const option = (value) => ({ name: 'format', description: 'Format', type: 'string', default: value }); +const parser = () => { const p = new CommandParser(); p.registerCommand({ name: 'root', description: '', options: [option('root')], subcommands: [{ name: 'child', description: '', options: [option('child')], subcommands: [{ name: 'nested', description: '', options: [option('nested')], subcommands: [{ name: 'deep', description: '', options: [option('deep')] }] }] }] }); return p; }; +test('nested and deep defaults take precedence over parent defaults', () => { + assert.equal(parser().parse(['root', 'child', 'nested']).flags.format, 'nested'); + assert.equal(parser().parse(['root', 'child', 'nested', 'deep']).flags.format, 'deep'); +}); +test('explicit values still override defaults', () => { + assert.equal(parser().parse(['root', 'child', 'nested', 'deep', '--format=json']).flags.format, 'json'); +}); diff --git a/tests/parser-positional-flags.test.mjs b/tests/parser-positional-flags.test.mjs new file mode 100644 index 0000000000..269e4ea2b3 --- /dev/null +++ b/tests/parser-positional-flags.test.mjs @@ -0,0 +1,19 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { CommandParser } from '../v3/@claude-flow/cli/src/parser.ts'; + +test('flags preserve positionals before and after them', () => { + const parser = new CommandParser(); + parser.registerCommand({ name: 'memory', description: 'Memory', action() {} }); + for (const args of [['memory', 'key', '--verbose', 'value'], ['memory', 'key', '--format=json']]) { + const result = parser.parse(args); + assert.deepEqual(result.flags._, result.positional); + assert.equal(result.flags._[0], 'key'); + } +}); + +test('flag values are excluded from positionals', () => { + const result = new CommandParser().parse(['key', '--config', 'config.json', 'value']); + assert.deepEqual(result.flags._, ['key', 'value']); + assert.equal(result.flags.config, 'config.json'); +}); diff --git a/tests/rate-status-burst.test.mjs b/tests/rate-status-burst.test.mjs new file mode 100644 index 0000000000..072a2498bd --- /dev/null +++ b/tests/rate-status-burst.test.mjs @@ -0,0 +1,14 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { RateLimiter } from '../v3/@claude-flow/cli/src/production/rate-limiter.ts'; +test('status reports the same burst capacity as admission checks', () => { + const limiter = new RateLimiter({ maxRequests: 2, burstMultiplier: 1.5 }); + assert.equal(limiter.getStatus('read').limit, 3); + for (let i = 0; i < 3; i++) { const r = limiter.check('read'); const s = limiter.getStatus('read'); assert.equal(s.remaining, r.remaining); assert.equal(s.current, i + 1); } + assert.equal(limiter.check('read').allowed, false); +}); +test('custom operation limits use the same rounded capacity', () => { + const limiter = new RateLimiter({ burstMultiplier: 1.5, operationLimits: { read: { maxRequests: 3, windowMs: 60000 } } }); + assert.equal(limiter.getStatus('read', 'user').limit, 4); + assert.equal(limiter.getStatus('read', 'user').remaining, 4); +}); diff --git a/tests/retry-exhausted-callbacks.test.mjs b/tests/retry-exhausted-callbacks.test.mjs new file mode 100644 index 0000000000..94eef5736b --- /dev/null +++ b/tests/retry-exhausted-callbacks.test.mjs @@ -0,0 +1,18 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import { withRetry } from '../v3/@claude-flow/cli/src/production/retry.ts'; +test('retry callbacks and history describe only actual retries', async () => { + for (const maxAttempts of [1, 3]) { + let calls = 0; const callbacks = []; + const result = await withRetry(async () => { calls++; throw new Error('failure'); }, { maxAttempts, initialDelayMs: 0, jitter: 0, shouldRetry: () => true, onRetry: (_, attempt) => callbacks.push(attempt) }); + assert.equal(calls, maxAttempts); + assert.equal(result.success, false); + assert.equal(result.retryHistory.length, maxAttempts - 1); + assert.deepEqual(callbacks, Array.from({ length: maxAttempts - 1 }, (_, i) => i + 1)); + } +}); +test('successful retry preserves prior retry history', async () => { + let calls = 0; + const result = await withRetry(async () => { if (++calls === 1) throw new Error('transient'); return 42; }, { initialDelayMs: 0, jitter: 0, shouldRetry: () => true }); + assert.equal(result.result, 42); assert.equal(result.retryHistory.length, 1); +}); diff --git a/v3/@claude-flow/cli/__tests__/plugins-transfer-deep.test.ts b/v3/@claude-flow/cli/__tests__/plugins-transfer-deep.test.ts index 378eeb4a1b..c67eccd7aa 100644 --- a/v3/@claude-flow/cli/__tests__/plugins-transfer-deep.test.ts +++ b/v3/@claude-flow/cli/__tests__/plugins-transfer-deep.test.ts @@ -1098,7 +1098,8 @@ describe('Rate Limiter', () => { limiter.check('op'); const status = limiter.getStatus('op'); expect(status.current).toBe(1); - expect(status.limit).toBe(10); + // status reports the same capacity admission uses: maxRequests 10 x default burstMultiplier 1.5 (#4006) + expect(status.limit).toBe(15); }); it('reset clears specific key', () => { diff --git a/v3/@claude-flow/cli/src/parser.ts b/v3/@claude-flow/cli/src/parser.ts index 026d18034e..4b9d0239fb 100644 --- a/v3/@claude-flow/cli/src/parser.ts +++ b/v3/@claude-flow/cli/src/parser.ts @@ -164,7 +164,6 @@ export class CommandParser { // command, because that's what caused `daemon start` to resolve as `start` // with `daemon` left as a positional. let resolvedCmd: Command | undefined; - let resolvedSub: Command | undefined; const resolvedCommands: Command[] = []; let sawFirstPositional = false; for (let index = 0; index < args.length; index++) { @@ -201,7 +200,6 @@ export class CommandParser { const child = parent.subcommands.find(sc => sc.name === arg || sc.aliases?.includes(arg)); if (child) { resolvedCommands.push(child); - resolvedSub ??= child; continue; } } @@ -209,10 +207,11 @@ export class CommandParser { break; } - const { aliases, booleanFlags, stringFlags } = this.getFlagScope(resolvedCommands); + const { aliases, booleanFlags, stringFlags, arrayFlags } = this.getFlagScope(resolvedCommands); let i = 0; let parsingFlags = true; + let commandSlotAvailable = true; while (i < args.length) { const arg = args[i]; @@ -228,8 +227,17 @@ export class CommandParser { if (parsingFlags && arg.startsWith('-')) { const parseResult = this.parseFlag(args, i, aliases, booleanFlags, stringFlags); + // Array declarations retain text and accumulate repeated occurrences. + for (const key of arrayFlags) { + const value = parseResult.flags[key]; + if (value !== undefined && value !== true && value !== false) { + const previous = result.flags[key]; + parseResult.flags[key] = [...(Array.isArray(previous) ? previous : []), String(value)]; + } + } // Apply to result flags - Object.assign(result.flags, parseResult.flags); + const { _: ignoredPositionals, ...parsedFlags } = parseResult.flags; + Object.assign(result.flags, parsedFlags); i = parseResult.nextIndex; continue; } @@ -238,7 +246,9 @@ export class CommandParser { // Fix for #1596: treat lazy command names as commands here too so that // downstream dispatch sees `commandPath = ['daemon', 'start']` instead of // `commandPath = ['start'], positional = ['daemon']`. - if (result.command.length === 0 && this.isKnownCommandName(arg)) { + const isCommandSlot = commandSlotAvailable && parsingFlags; + commandSlotAvailable = false; + if (isCommandSlot && this.isKnownCommandName(arg)) { // This is a command result.command.push(arg); @@ -287,7 +297,7 @@ export class CommandParser { // `default: true` silently dropped and reached the action handler as // `undefined`. That trapped `memory store --upsert` and every other // subcommand that leaned on a per-flag default. - this.applyDefaults(result.flags, resolvedCmd, resolvedSub); + this.applyDefaults(result.flags, resolvedCommands); return result; } @@ -521,6 +531,7 @@ export class CommandParser { aliases: Record; booleanFlags: Set; stringFlags: Set; + arrayFlags: Set; } { const aliases = this.buildScopedAliases(commands[commands.length - 1]); const booleanFlags = this.getScopedBooleanFlags(commands[commands.length - 1]); @@ -530,18 +541,22 @@ export class CommandParser { if (option.short) aliases[option.short] = option.name; } } + const arrayFlags = new Set((this.options.arrayFlags ?? []).map(flag => this.normalizeKey(flag))); + for (const flag of arrayFlags) stringFlags.add(flag); const layers = [this.globalOptions, ...commands.map(command => command.options ?? [])]; for (const options of layers) { for (const option of options) { const key = this.normalizeKey(option.name); - if (option.type === 'string') stringFlags.add(key); + if (option.type === 'array') arrayFlags.add(key); + else if (option.type) arrayFlags.delete(key); + if (option.type === 'string' || option.type === 'array') stringFlags.add(key); else if (option.type) stringFlags.delete(key); if (option.type === 'boolean') booleanFlags.add(key); else if (option.type) booleanFlags.delete(key); } } for (const flag of stringFlags) booleanFlags.delete(flag); - return { aliases, booleanFlags, stringFlags }; + return { aliases, booleanFlags, stringFlags, arrayFlags }; } private getBooleanFlags(): Set { @@ -585,22 +600,17 @@ export class CommandParser { return flags; } - private applyDefaults(flags: ParsedFlags, command?: Command, subcommand?: Command): void { - // #2775: apply defaults from globals AND the resolved command/subcommand. - // Subcommand > command > global (later writes lose to earlier — because - // we only set when `undefined`, so the FIRST option definition that - // supplies a default wins; walk narrow-to-broad so subcommand options - // apply before broader ones do). - const layers: CommandOption[][] = []; - if (subcommand?.options) layers.push(subcommand.options); - if (command?.options) layers.push(command.options); + private applyDefaults(flags: ParsedFlags, commands: Command[]): void { + // Walk every resolved command from narrow to broad so nested defaults + // have the same precedence as their declared flag types. + const layers = [...commands].reverse().map(command => command.options ?? []); layers.push(this.globalOptions); for (const layer of layers) { for (const opt of layer) { const key = this.normalizeKey(opt.name); if (flags[key] === undefined && opt.default !== undefined) { - flags[key] = opt.default as string | boolean | number | string[]; + flags[key] = (Array.isArray(opt.default) ? [...opt.default] : opt.default) as string | boolean | number | string[]; } } } @@ -610,7 +620,7 @@ export class CommandParser { for (const [key, value] of Object.entries(this.options.defaults)) { const normalizedKey = this.normalizeKey(key); if (flags[normalizedKey] === undefined) { - flags[normalizedKey] = value as string | boolean | number | string[]; + flags[normalizedKey] = (Array.isArray(value) ? [...value] : value) as string | boolean | number | string[]; } } } @@ -636,7 +646,7 @@ export class CommandParser { // followed by another flag) is parsed as boolean `true`. Commands then treat `true` as // the value: `hooks route --task` crashed with "task.trim is not a function" and // `memory retrieve --key` looked up the key "true". Report it instead. - if ((opt.type === 'string' || opt.type === 'number') && flags[key] === true) { + if ((opt.type === 'string' || opt.type === 'number' || opt.type === 'array') && flags[key] === true) { errors.push(`Option --${opt.name} needs a value`); } diff --git a/v3/@claude-flow/cli/src/production/monitoring.ts b/v3/@claude-flow/cli/src/production/monitoring.ts index 15298fad19..3120870f6a 100644 --- a/v3/@claude-flow/cli/src/production/monitoring.ts +++ b/v3/@claude-flow/cli/src/production/monitoring.ts @@ -110,6 +110,7 @@ export class MonitoringHooks { private healthStatus: HealthStatus; private startTime = Date.now(); private activeRequests = 0; + private requestGeneration = 0; private requestCount = 0; private errorCount = 0; private healthChecks: Map Promise<{ healthy: boolean; message?: string }>> = new Map(); @@ -191,10 +192,14 @@ export class MonitoringHooks { this.requestCount++; const startTime = Date.now(); + const generation = this.requestGeneration; + let completed = false; this.counter('request_started', 1, { requestId }); // Return end function return () => { + if (completed || generation !== this.requestGeneration) return; + completed = true; this.activeRequests--; const duration = Date.now() - startTime; this.responseTimes.push(duration); @@ -254,7 +259,7 @@ export class MonitoringHooks { } catch (error) { checks[name] = { status: 'unhealthy', - message: (error as Error).message, + message: error instanceof Error ? error.message : String(error), lastCheck: Date.now(), responseTimeMs: Date.now() - startTime, }; @@ -268,14 +273,14 @@ export class MonitoringHooks { timestamp: Date.now(), }; - return this.healthStatus; + return structuredClone(this.healthStatus); } /** * Get current health status */ getHealthStatus(): HealthStatus { - return this.healthStatus; + return structuredClone(this.healthStatus); } // ============================================================================ @@ -324,7 +329,7 @@ export class MonitoringHooks { if (level) { filtered = filtered.filter(a => a.level === level); } - return filtered; + return filtered.map(alert => ({ ...alert })); } /** @@ -359,7 +364,7 @@ export class MonitoringHooks { if (since) { filtered = filtered.filter(m => m.timestamp >= since); } - return filtered; + return filtered.map(metric => ({ ...metric, labels: { ...metric.labels } })); } /** @@ -394,6 +399,7 @@ export class MonitoringHooks { * Reset all metrics */ reset(): void { + this.requestGeneration++; this.metrics = []; this.responseTimes = []; this.alerts = []; @@ -430,7 +436,12 @@ export class MonitoringHooks { Date.now() - a.timestamp < 60000 ); - if (!recentAlert) { + if (recentAlert && level === 'critical' && recentAlert.level !== 'critical') { + Object.assign(recentAlert, { + level, value, threshold, timestamp: Date.now(), + message: `${name} exceeded ${level} threshold: ${value} >= ${threshold}`, + }); + } else if (!recentAlert) { this.alerts.push({ id: `alert_${Date.now()}_${Math.random().toString(36).substring(7)}`, level, diff --git a/v3/@claude-flow/cli/src/production/rate-limiter.ts b/v3/@claude-flow/cli/src/production/rate-limiter.ts index 49febf1f02..821b75ce8d 100644 --- a/v3/@claude-flow/cli/src/production/rate-limiter.ts +++ b/v3/@claude-flow/cli/src/production/rate-limiter.ts @@ -152,6 +152,7 @@ export class RateLimiter { resetAt: number; } { const limits = this.getLimits(operation); + const capacity = Math.floor(limits.maxRequests * this.config.burstMultiplier); const bucketKey = userId && this.config.perUserLimits ? `${operation}:${userId}` : `global:${operation}`; @@ -162,8 +163,8 @@ export class RateLimiter { if (!bucket) { return { current: 0, - limit: limits.maxRequests, - remaining: limits.maxRequests, + limit: capacity, + remaining: capacity, resetAt: now + limits.windowMs, }; } @@ -173,8 +174,8 @@ export class RateLimiter { return { current: validRequests.length, - limit: limits.maxRequests, - remaining: Math.max(0, limits.maxRequests - validRequests.length), + limit: capacity, + remaining: Math.max(0, capacity - validRequests.length), resetAt: validRequests.length > 0 ? validRequests[0] + limits.windowMs : now + limits.windowMs, diff --git a/v3/@claude-flow/cli/src/production/retry.ts b/v3/@claude-flow/cli/src/production/retry.ts index ef9134e9fd..b5ab6186f7 100644 --- a/v3/@claude-flow/cli/src/production/retry.ts +++ b/v3/@claude-flow/cli/src/production/retry.ts @@ -129,6 +129,9 @@ function shouldRetryError( attempt: number, config: RetryConfig ): boolean { + // Exhaustion always takes precedence over custom retry policies. + if (attempt >= config.maxAttempts) return false; + // Check custom retry function if (config.shouldRetry) { return config.shouldRetry(error, attempt); diff --git a/v3/@claude-flow/cli/src/services/config-file-manager.ts b/v3/@claude-flow/cli/src/services/config-file-manager.ts index 4e5f4d84e9..c26c038bd3 100644 --- a/v3/@claude-flow/cli/src/services/config-file-manager.ts +++ b/v3/@claude-flow/cli/src/services/config-file-manager.ts @@ -131,15 +131,15 @@ export class ConfigFileManager { this.selectProject(cwd); // A targeted update must not persist unrelated defaults (notably the // default memory path, which would relocate an existing memory store). - const config = this.config ?? this.load(cwd) ?? {}; + const config = structuredClone(this.config ?? this.load(cwd) ?? {}); if (Object.hasOwn(config, key)) { config[key] = value; } else { setNestedValue(config, key, value); } - this.config = config; const targetPath = this.configPath ?? path.resolve(cwd, CONFIG_FILENAMES[0]); this.writeAtomic(targetPath, config); + this.config = config; this.configPath = targetPath; } @@ -282,7 +282,7 @@ export function parseConfigValue(value: string): unknown { if (/^\d+\.\d+$/.test(value)) return parseFloat(value); try { const parsed = JSON.parse(value); - if (typeof parsed === 'object') return parsed; + if (typeof parsed === 'object' || (typeof parsed === 'number' && Number.isFinite(parsed))) return parsed; } catch { /* not JSON, use as string */ } return value; }