Files
ruflo/v3/@claude-flow/cli/__tests__
Nicholas RuestandRuFlo 0a23ae4487 fix(memory): make the WAL-sidecar safety gate liveness-based, not presence-based (#3161)
hasNativeWalSidecars() (#2735) refused every whole-image sql.js write/list
against memory.db whenever -wal/-shm sidecars merely existed on disk, on the
assumption that sidecars are only ever present while a native better-sqlite3
WAL connection is live. ruflo doctor breaks that assumption: it opens several
readonly native connections for diagnostics and closes them with a plain
.close(), which does not checkpoint and leaves orphaned sidecars behind. Once
that happens, every later memory store/list in the project fails permanently
with a misleading "active native WAL connection" error until someone deletes
the sidecar files by hand — the tool users are told to run when something is
wrong is what causes this.

hasNativeWalSidecars() now probes liveness in two steps instead of trusting
presence alone: 1) open our own connection and run
wal_checkpoint(TRUNCATE) — busy !== 0 means a real holder has an open
transaction right now, refuse immediately (also truncates a genuinely
orphaned WAL as a side effect); 2) otherwise close our probe connection and
re-check whether the sidecars are still on disk. SQLite only deletes
-wal/-shm when the last connection closes, so if nothing else is attached,
our own close is that last close and the sidecars vanish — safe to proceed.
If they're still present after our own close, some other connection remains
attached even though idle (holding no lock, so step 1 alone would have
missed it) — still refuse. This preserves #2735's guarantee for a genuinely
live holder (including the idle-but-attached case #3397's test exercises)
while fixing the false positive from an orphan. The no-sidecar fast path is
unchanged: a couple of existsSync calls, no database connection opened.

Rewrote issue-2735's and memory-cli-mirror-removal's sidecar fixtures to use
real WAL-mode databases with genuine transactions instead of empty
touch-files, since presence-only fixtures no longer exercise anything
meaningful against a liveness-based gate. Added issue-3161-doctor-leak-
recovery.test.ts (reproduces doctor's actual leak pattern and confirms a
subsequent store/list self-heals instead of failing permanently) and
issue-3161-wal-liveness-probe.test.ts (genuine live writer still refused,
concurrent callers, probe-error fail-closed, no-sidecar fast path never
opens a connection).

Co-Authored-By: RuFlo <ruv@ruv.net>
2026-10-07 15:39:08 -04:00
..
2026-01-04 20:41:12 +00:00
2026-01-04 20:37:19 +00:00
2026-01-04 20:37:19 +00:00

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 inputs
  • getToolMetadata() - Metadata retrieval
  • listMCPTools() - Tool listing and filtering by category
  • hasTool() - Tool existence checks
  • getToolCategories() - Category enumeration
  • validateToolInput() - Input validation against schemas
  • MCPClientError - 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 operations
  • swarm-tools.js - Mocked swarm coordination
  • memory-tools.js - Mocked memory operations
  • config-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