Files
claude-mem/tests/worker-spawn.test.ts
Alex Newman f38b5b85bc fix: resolve issues #543, #544, #545, #557 (#558)
* docs: add investigation reports for 5 open GitHub issues

Comprehensive analysis of issues #543, #544, #545, #555, and #557:

- #557: settings.json not generated, module loader error (node/bun mismatch)
- #555: Windows hooks not executing, hasIpc always false
- #545: formatTool crashes on non-JSON tool_input strings
- #544: mem-search skill hint shown incorrectly to Claude Code users
- #543: /claude-mem slash command unavailable despite installation

Each report includes root cause analysis, affected files, and proposed fixes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(logger): handle non-JSON tool_input in formatTool (#545)

Wrap JSON.parse in try-catch to handle raw string inputs (e.g., Bash
commands) that aren't valid JSON. Falls back to using the string as-is.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(context): update mem-search hint to reference MCP tools (#544)

Update hint messages to reference MCP tools (search, get_observations)
instead of the deprecated "mem-search skill" terminology.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(settings): auto-create settings.json on first load (#557, #543)

When settings.json doesn't exist, create it with defaults instead of
returning in-memory defaults. Creates parent directory if needed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(hooks): use bun runtime for hooks except smart-install (#557)

Change hook commands from node to bun since hooks use bun:sqlite.
Keep smart-install.js on node since it bootstraps bun installation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* chore: rebuild plugin scripts

* docs: clarify that build artifacts must be committed

* fix(docs): update build artifacts directory reference in CLAUDE.md

* test: add test coverage for PR #558 fixes

- Fix 2 failing tests: update "mem-search skill" → "MCP tools" expectations
- Add 56 tests for formatTool() JSON.parse crash fix (Issue #545)
- Add 27 tests for settings.json auto-creation (Issue #543)

Test coverage includes:
- formatTool: JSON parsing, raw strings, objects, null/undefined, all tool types
- Settings: file creation, directory creation, schema migration, edge cases

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix(tests): clean up flaky tests and fix circular dependency

Phase 1 of test quality improvements:

- Delete 6 harmful/worthless test files that used problematic mock.module()
  patterns or tested implementation details rather than behavior:
  - context-builder.test.ts (tested internal implementation)
  - export-types.test.ts (fragile mock patterns)
  - smart-install.test.ts (shell script testing antipattern)
  - session_id_refactor.test.ts (outdated, tested refactoring itself)
  - validate_sql_update.test.ts (one-time migration validation)
  - observation-broadcaster.test.ts (excessive mocking)

- Fix circular dependency between logger.ts and SettingsDefaultsManager.ts
  by using late binding pattern - logger now lazily loads settings

- Refactor mock.module() to spyOn() in several test files for more
  maintainable and less brittle tests:
  - observation-compiler.test.ts
  - gemini_agent.test.ts
  - error-handler.test.ts
  - server.test.ts
  - response-processor.test.ts

All 649 tests pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor(tests): phase 2 - reduce mock-heavy tests and improve focus

- Remove mock-heavy query tests from observation-compiler.test.ts, keep real buildTimeline tests
- Convert session_id_usage_validation.test.ts from 477 to 178 lines of focused smoke tests
- Remove tests for language built-ins from worker-spawn.test.ts (JSON.parse, array indexing)
- Rename logger-coverage.test.ts to logger-usage-standards.test.ts for clarity

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* docs(tests): phase 3 - add JSDoc mock justification to test files

Document mock usage rationale in 5 test files to improve maintainability:
- error-handler.test.ts: Express req/res mocks, logger spies (~11%)
- fallback-error-handler.test.ts: Zero mocks, pure function tests
- session-cleanup-helper.test.ts: Session fixtures, worker mocks (~19%)
- hook-constants.test.ts: process.platform mock for Windows tests (~12%)
- session_store.test.ts: Zero mocks, real SQLite :memory: database

Part of ongoing effort to document mock justifications per TESTING.md guidelines.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test(integration): phase 5 - add 72 tests for critical coverage gaps

Add comprehensive test coverage for previously untested areas:

- tests/integration/hook-execution-e2e.test.ts (10 tests)
  Tests lifecycle hooks execution flow and context propagation

- tests/integration/worker-api-endpoints.test.ts (19 tests)
  Tests all worker service HTTP endpoints without heavy mocking

- tests/integration/chroma-vector-sync.test.ts (16 tests)
  Tests vector embedding synchronization with ChromaDB

- tests/utils/tag-stripping.test.ts (27 tests)
  Tests privacy tag stripping utilities for both <private> and
  <meta-observation> tags

All tests use real implementations where feasible, following the
project's testing philosophy of preferring integration-style tests
over unit tests with extensive mocking.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* context update

* docs: add comment linking DEFAULT_DATA_DIR locations

Added NOTE comment in logger.ts pointing to the canonical DEFAULT_DATA_DIR
in SettingsDefaultsManager.ts. This addresses PR reviewer feedback about
the fragility of having the default defined in two places to avoid
circular dependencies.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 19:45:09 -05:00

221 lines
6.6 KiB
TypeScript

import { describe, it, expect, beforeAll, afterAll, afterEach } from 'bun:test';
import { execSync, ChildProcess } from 'child_process';
import { existsSync, readFileSync, writeFileSync, unlinkSync, mkdirSync, rmSync } from 'fs';
import { homedir } from 'os';
import path from 'path';
/**
* Worker Self-Spawn Integration Tests
*
* Tests actual integration points:
* - Health check utilities (real network behavior)
* - PID file management (real filesystem)
* - Status command output format
* - Windows-specific behavior detection
*
* Removed: JSON.parse tests, CLI command parsing (tests language built-ins)
*/
const TEST_PORT = 37877;
const TEST_DATA_DIR = path.join(homedir(), '.claude-mem-test');
const TEST_PID_FILE = path.join(TEST_DATA_DIR, 'worker.pid');
const WORKER_SCRIPT = path.join(__dirname, '../plugin/scripts/worker-service.cjs');
interface PidInfo {
pid: number;
port: number;
startedAt: string;
}
/**
* Helper to check if port is in use by attempting a health check
*/
async function isPortInUse(port: number): Promise<boolean> {
try {
const response = await fetch(`http://127.0.0.1:${port}/api/health`, {
signal: AbortSignal.timeout(2000)
});
return response.ok;
} catch {
return false;
}
}
/**
* Helper to wait for port to be healthy
*/
async function waitForHealth(port: number, timeoutMs: number = 30000): Promise<boolean> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (await isPortInUse(port)) return true;
await new Promise(r => setTimeout(r, 500));
}
return false;
}
/**
* Run worker CLI command and return stdout
*/
function runWorkerCommand(command: string, env: Record<string, string> = {}): string {
const result = execSync(`bun "${WORKER_SCRIPT}" ${command}`, {
env: { ...process.env, ...env },
encoding: 'utf-8',
timeout: 60000
});
return result.trim();
}
describe('Worker Self-Spawn CLI', () => {
beforeAll(async () => {
if (existsSync(TEST_DATA_DIR)) {
rmSync(TEST_DATA_DIR, { recursive: true });
}
});
afterAll(async () => {
if (existsSync(TEST_DATA_DIR)) {
rmSync(TEST_DATA_DIR, { recursive: true });
}
});
describe('status command', () => {
it('should report worker status in expected format', async () => {
const output = runWorkerCommand('status');
// Should contain either "running" or "not running"
expect(output.includes('running')).toBe(true);
});
it('should include PID and port when running', async () => {
const output = runWorkerCommand('status');
if (output.includes('Worker running')) {
expect(output).toMatch(/PID: \d+/);
expect(output).toMatch(/Port: \d+/);
}
});
});
describe('PID file management', () => {
it('should create and read PID file with correct structure', () => {
mkdirSync(TEST_DATA_DIR, { recursive: true });
const testPidInfo: PidInfo = {
pid: 12345,
port: TEST_PORT,
startedAt: new Date().toISOString()
};
writeFileSync(TEST_PID_FILE, JSON.stringify(testPidInfo, null, 2));
expect(existsSync(TEST_PID_FILE)).toBe(true);
const readInfo = JSON.parse(readFileSync(TEST_PID_FILE, 'utf-8')) as PidInfo;
expect(readInfo.pid).toBe(12345);
expect(readInfo.port).toBe(TEST_PORT);
expect(readInfo.startedAt).toBe(testPidInfo.startedAt);
// Cleanup
unlinkSync(TEST_PID_FILE);
expect(existsSync(TEST_PID_FILE)).toBe(false);
});
});
describe('health check utilities', () => {
it('should return false for non-existent server', async () => {
const unusedPort = 39999;
const result = await isPortInUse(unusedPort);
expect(result).toBe(false);
});
it('should timeout appropriately for unreachable server', async () => {
const start = Date.now();
const result = await isPortInUse(39998);
const elapsed = Date.now() - start;
expect(result).toBe(false);
// Should not wait longer than the timeout (2s) + small buffer
expect(elapsed).toBeLessThan(3000);
});
});
});
describe('Worker Health Endpoints', () => {
let workerProcess: ChildProcess | null = null;
beforeAll(async () => {
// Skip if worker script doesn't exist (not built)
if (!existsSync(WORKER_SCRIPT)) {
console.log('Skipping worker health tests - worker script not built');
return;
}
});
afterAll(async () => {
if (workerProcess) {
workerProcess.kill('SIGTERM');
workerProcess = null;
}
});
describe('health endpoint contract', () => {
it('should expect /api/health to return status ok with expected fields', async () => {
// Contract validation: verify expected response structure
const mockResponse = {
status: 'ok',
build: 'TEST-008-wrapper-ipc',
managed: false,
hasIpc: false,
platform: 'darwin',
pid: 12345,
initialized: true,
mcpReady: true
};
expect(mockResponse.status).toBe('ok');
expect(typeof mockResponse.build).toBe('string');
expect(typeof mockResponse.pid).toBe('number');
expect(typeof mockResponse.managed).toBe('boolean');
expect(typeof mockResponse.initialized).toBe('boolean');
});
it('should expect /api/readiness to distinguish ready vs initializing states', async () => {
const readyResponse = { status: 'ready', mcpReady: true };
const initializingResponse = { status: 'initializing', message: 'Worker is still initializing, please retry' };
expect(readyResponse.status).toBe('ready');
expect(initializingResponse.status).toBe('initializing');
});
});
});
describe('Windows-specific behavior', () => {
const originalPlatform = process.platform;
afterEach(() => {
Object.defineProperty(process, 'platform', {
value: originalPlatform,
writable: true,
configurable: true
});
delete process.env.CLAUDE_MEM_MANAGED;
});
it('should detect Windows managed worker mode correctly', () => {
Object.defineProperty(process, 'platform', {
value: 'win32',
writable: true,
configurable: true
});
process.env.CLAUDE_MEM_MANAGED = 'true';
const isWindows = process.platform === 'win32';
const isManaged = process.env.CLAUDE_MEM_MANAGED === 'true';
expect(isWindows).toBe(true);
expect(isManaged).toBe(true);
// In non-managed mode (without process.send), IPC messages won't work
const hasProcessSend = typeof process.send === 'function';
const isWindowsManaged = isWindows && isManaged && hasProcessSend;
expect(isWindowsManaged).toBe(false); // No process.send in test context
});
});