* feat(daemon): repository supervisor, structured telemetry, budget CLI, migration warning (#2661)
Closes the four gaps flagged as still-open against #2661's full root-fix
spec after the containment + dedup phases already shipped (#2662).
1. Repository-level supervisor + worktree leases (workspace-lease.ts,
repo-supervisor.ts). Ten worktree daemons of one repository independently
deciding "is it time to run audit" every tick was the redundant-scheduler
half of the cardinality bug — the budget ledger and job dedup already
bound and dedupe actual spend, but every daemon still ran its own timer.
Exactly one daemon per repositoryId is now elected supervisor (lock-
protected takeover, same pattern as global-ai-budget.ts) and owns the
recurring AI-worker schedule; every other worktree stays a lease-only
participant (15-min TTL heartbeat) running its cheap local-only workers.
An explicit `daemon trigger --headless` still bypasses the gate — it's a
one-off user action, still budget/dedup-governed like any other launch.
2. Structured per-launch token telemetry. `claude --print` now runs with
`--output-format json`; parseClaudePrintJsonEnvelope() extracts input/
output tokens, cost, and API duration, receipted via the budget ledger's
new recordUsage(). Lenient parsing — any schema mismatch degrades to
"no usage captured" rather than breaking existing analysis-output
parsing, since the raw `result` text still flows through unchanged.
3. `ruflo daemon budget show|pause|resume`. Budget state was previously
visible only inline in `daemon status --all`; these give it an
independently scriptable surface. pause()/resume() reuse the exact same
enforcement path as the automatic quota-triggered circuit breaker.
4. One-time upgrade migration warning. A pre-existing multi-daemon fleet
where AI workers were already enabled (old config/env from before this
fix) is exactly the P0 shape #2661 describes — warned once ever (a
persisted marker, not per-command), and only for that specific risky
shape, not a harmless AI-off fleet (already covered by the existing
always-shown fleet-size notice).
`daemon status --all` gains a "Repository Supervisors" panel alongside the
existing budget panel.
54 new tests across workspace-lease, repo-supervisor, claude-print-envelope,
global-ai-budget (extended), and daemon-migration-warning-2661 suites.
Co-Authored-By: RuFlo <ruv@ruv.net>
* fix(statusline): don't import helper-refresh.js just for getInstalledCliVersion
statusline-generator.ts imported getInstalledCliVersion from helper-refresh.js
(added in b254e3215, shipped 3.27.3-3.27.4). ES module imports load a
module's ENTIRE top-level regardless of which export is used — helper-
refresh.ts imports the `semver` package at module scope (for
autoRefreshHelpersIfStale()'s version comparison, unrelated to the function
actually needed here), so merely importing getInstalledCliVersion dragged
`semver` into every context that loads this generator.
Confirmed live: PR #2663's "Static regression guards" CI job installs only
minimal smoke deps (no full `npm install`), and helpers-generator.ts
transitively imports statusline-generator.ts — the router smoke test
(#2257) failed with ERR_MODULE_NOT_FOUND('semver') the moment this file
gained the import, despite never calling anything semver-related itself.
Verified by temporarily hiding node_modules/semver locally: reproduced the
exact failure, confirmed fixed after this change.
Duplicates the same createRequire/walk-up version resolution locally
(getInstalledCliVersionLocal) using only Node builtins — this generator's
own footprint should stay minimal since it's loaded in exactly these
lightweight/partial-install contexts. No output change: the baked-in
version value and the rest of the generated script are byte-identical.
Co-Authored-By: RuFlo <ruv@ruv.net>
CLI Module Tests
This directory contains comprehensive tests for the V3 CLI module using Vitest.
Test Files
1. cli.test.ts (~15+ tests)
Tests for the main CLI class covering:
- Version command (
--version,-V) - Help output (
--help,-h) - Command parsing (long flags, short flags, equals syntax)
- Positional arguments
- Boolean flags and negation
- Global flags (
--quiet,--format,--config,--no-color) - Error handling (unknown commands, missing options)
- Subcommand execution and aliases
- Exit codes
2. mcp-client.test.ts (~10+ tests)
Tests for MCP tool invocation:
callMCPTool()- Tool execution with various inputsgetToolMetadata()- Metadata retrievallistMCPTools()- Tool listing and filtering by categoryhasTool()- Tool existence checksgetToolCategories()- Category enumerationvalidateToolInput()- Input validation against schemasMCPClientError- Custom error handling
3. commands.test.ts (~48+ tests)
Tests for all CLI commands:
Agent Commands (spawn, list, status, stop, metrics):
- Spawning agents with various configurations
- Listing agents with filters
- Getting agent status and metrics
- Stopping agents (graceful/force)
- Agent performance metrics
Swarm Commands (init, start, status, stop, scale, coordinate):
- Initializing swarms with different topologies
- Starting swarm execution with objectives
- Checking swarm status
- Stopping and scaling swarms
- V3 15-agent coordination structure
Memory Commands (store, retrieve, search, list, delete, stats, configure):
- Storing data in memory (with/without vectors)
- Retrieving data by key
- Semantic/vector search
- Listing memory entries
- Deleting entries
- Viewing statistics
- Backend configuration
Config Commands (init, get, set, providers, reset, export, import):
- Initializing configuration
- Getting/setting config values
- Managing AI providers
- Resetting to defaults
- Exporting/importing configuration
Mocking Strategy
MCP Tools
All MCP tools are mocked at the module level to prevent actual tool execution:
agent-tools.js- Mocked agent operationsswarm-tools.js- Mocked swarm coordinationmemory-tools.js- Mocked memory operationsconfig-tools.js- Mocked configuration
Output
The output module is fully mocked to capture formatted output without console pollution.
Prompts
Interactive prompts (select, confirm, input, multiSelect) are mocked to return default values for non-interactive testing.
Process
process.exit() is mocked to throw errors instead of terminating the test process.
Running Tests
# Run all CLI tests
npm test -- v3/@claude-flow/cli/__tests__/
# Run specific test file
npm test -- v3/@claude-flow/cli/__tests__/cli.test.ts
# Run with coverage
npm test -- v3/@claude-flow/cli/__tests__/ --coverage
# Run in watch mode
npm test -- v3/@claude-flow/cli/__tests__/ --watch
Test Coverage Goals
- Statements: >80%
- Branches: >75%
- Functions: >80%
- Lines: >80%
Key Testing Patterns
1. Command Execution
const result = await command.action!(ctx);
expect(result.success).toBe(true);
expect(result.data).toHaveProperty('expectedField');
2. Flag Parsing
ctx.flags = { myFlag: 'value', _: [] };
await command.action!(ctx);
// Assertions in action callback
3. Error Handling
try {
await cli.run(['invalid-command']);
} catch (e) {
expect((e as Error).message).toContain('process.exit');
}
4. Output Validation
const output = consoleOutput.join('');
expect(output).toContain('Expected text');
Notes
- All tests are non-interactive (
interactive: false) - Console output is captured for verification
- Process exits are converted to exceptions
- MCP client is fully isolated from actual MCP server
- Tests use unique command names to avoid conflicts