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>
This commit is contained in:
Alex Newman
2026-01-05 19:45:09 -05:00
committed by GitHub
parent f1ccc22593
commit f38b5b85bc
55 changed files with 4712 additions and 2676 deletions
+33 -162
View File
@@ -1,18 +1,26 @@
import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll } from 'bun:test';
import { spawn, execSync, ChildProcess } from 'child_process';
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';
// Test configuration
const TEST_PORT = 37877; // Use different port than default to avoid conflicts
/**
* 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');
// Timeout for health checks
const HEALTH_TIMEOUT_MS = 5000;
interface PidInfo {
pid: number;
port: number;
@@ -45,33 +53,6 @@ async function waitForHealth(port: number, timeoutMs: number = 30000): Promise<b
return false;
}
/**
* Helper to wait for port to be free
*/
async function waitForPortFree(port: number, timeoutMs: number = 10000): 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;
}
/**
* Helper to shut down worker via HTTP
*/
async function httpShutdown(port: number): Promise<boolean> {
try {
await fetch(`http://127.0.0.1:${port}/api/admin/shutdown`, {
method: 'POST',
signal: AbortSignal.timeout(5000)
});
return true;
} catch {
return false;
}
}
/**
* Run worker CLI command and return stdout
*/
@@ -86,14 +67,12 @@ function runWorkerCommand(command: string, env: Record<string, string> = {}): st
describe('Worker Self-Spawn CLI', () => {
beforeAll(async () => {
// Clean up test data directory
if (existsSync(TEST_DATA_DIR)) {
rmSync(TEST_DATA_DIR, { recursive: true });
}
});
afterAll(async () => {
// Clean up test data directory
if (existsSync(TEST_DATA_DIR)) {
rmSync(TEST_DATA_DIR, { recursive: true });
}
@@ -101,19 +80,13 @@ describe('Worker Self-Spawn CLI', () => {
describe('status command', () => {
it('should report worker status in expected format', async () => {
// The status command reads from settings file, not env vars
// Just verify the output format is correct (running or not running)
const output = runWorkerCommand('status');
// Should contain either "running" or "not running"
const hasValidStatus = output.includes('running');
expect(hasValidStatus).toBe(true);
expect(output.includes('running')).toBe(true);
});
it('should include PID and port when running', async () => {
const output = runWorkerCommand('status');
// If running, should include PID and port
if (output.includes('Worker running')) {
expect(output).toMatch(/PID: \d+/);
expect(output).toMatch(/Port: \d+/);
@@ -122,8 +95,7 @@ describe('Worker Self-Spawn CLI', () => {
});
describe('PID file management', () => {
it('should create PID file with correct structure', () => {
// Create test directory
it('should create and read PID file with correct structure', () => {
mkdirSync(TEST_DATA_DIR, { recursive: true });
const testPidInfo: PidInfo = {
@@ -133,28 +105,15 @@ describe('Worker Self-Spawn CLI', () => {
};
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);
});
it('should handle missing PID file gracefully', () => {
const missingPath = path.join(TEST_DATA_DIR, 'nonexistent.pid');
expect(existsSync(missingPath)).toBe(false);
});
it('should remove PID file correctly', () => {
mkdirSync(TEST_DATA_DIR, { recursive: true });
writeFileSync(TEST_PID_FILE, JSON.stringify({ pid: 1, port: 1, startedAt: '' }));
expect(existsSync(TEST_PID_FILE)).toBe(true);
// Cleanup
unlinkSync(TEST_PID_FILE);
expect(existsSync(TEST_PID_FILE)).toBe(false);
});
});
@@ -176,16 +135,6 @@ describe('Worker Self-Spawn CLI', () => {
expect(elapsed).toBeLessThan(3000);
});
});
describe('hook response format', () => {
it('should return valid JSON hook response', () => {
const hookResponse = '{"continue": true, "suppressOutput": true}';
const parsed = JSON.parse(hookResponse);
expect(parsed.continue).toBe(true);
expect(parsed.suppressOutput).toBe(true);
});
});
});
describe('Worker Health Endpoints', () => {
@@ -197,9 +146,6 @@ describe('Worker Health Endpoints', () => {
console.log('Skipping worker health tests - worker script not built');
return;
}
// Start worker for health endpoint tests using default port
// Note: These tests use the real worker, so they may be affected by existing worker state
});
afterAll(async () => {
@@ -210,20 +156,8 @@ describe('Worker Health Endpoints', () => {
});
describe('health endpoint contract', () => {
it('should expect /api/health to return status ok', async () => {
// This is a contract test - validates expected format
const expectedHealthResponse = {
status: 'ok',
build: expect.any(String),
managed: expect.any(Boolean),
hasIpc: expect.any(Boolean),
platform: expect.any(String),
pid: expect.any(Number),
initialized: expect.any(Boolean),
mcpReady: expect.any(Boolean)
};
// Verify the contract structure matches what the code returns
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',
@@ -238,25 +172,16 @@ describe('Worker Health Endpoints', () => {
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 return status when ready', async () => {
const expectedReadyResponse = {
status: 'ready',
mcpReady: true
};
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(expectedReadyResponse.status).toBe('ready');
expect(expectedReadyResponse.mcpReady).toBe(true);
});
it('should expect /api/readiness to return 503 when initializing', async () => {
const expectedInitializingResponse = {
status: 'initializing',
message: 'Worker is still initializing, please retry'
};
expect(expectedInitializingResponse.status).toBe('initializing');
expect(readyResponse.status).toBe('ready');
expect(initializingResponse.status).toBe('initializing');
});
});
});
@@ -270,32 +195,15 @@ describe('Windows-specific behavior', () => {
writable: true,
configurable: true
});
delete process.env.CLAUDE_MEM_MANAGED;
});
it('should use different shutdown behavior on Windows', () => {
it('should detect Windows managed worker mode correctly', () => {
Object.defineProperty(process, 'platform', {
value: 'win32',
writable: true,
configurable: true
});
// Windows uses IPC messages for managed workers
const isWindowsManaged = process.platform === 'win32' &&
process.env.CLAUDE_MEM_MANAGED === 'true' &&
typeof process.send === 'function';
// In non-managed mode, this should be false
expect(isWindowsManaged).toBe(false);
});
it('should identify managed Windows worker correctly', () => {
Object.defineProperty(process, 'platform', {
value: 'win32',
writable: true,
configurable: true
});
// Set managed environment
process.env.CLAUDE_MEM_MANAGED = 'true';
const isWindows = process.platform === 'win32';
@@ -304,46 +212,9 @@ describe('Windows-specific behavior', () => {
expect(isWindows).toBe(true);
expect(isManaged).toBe(true);
// Cleanup
delete process.env.CLAUDE_MEM_MANAGED;
});
});
describe('CLI command parsing', () => {
it('should recognize start command', () => {
const args = ['node', 'worker-service.cjs', 'start'];
const command = args[2];
expect(command).toBe('start');
});
it('should recognize stop command', () => {
const args = ['node', 'worker-service.cjs', 'stop'];
const command = args[2];
expect(command).toBe('stop');
});
it('should recognize restart command', () => {
const args = ['node', 'worker-service.cjs', 'restart'];
const command = args[2];
expect(command).toBe('restart');
});
it('should recognize status command', () => {
const args = ['node', 'worker-service.cjs', 'status'];
const command = args[2];
expect(command).toBe('status');
});
it('should recognize --daemon flag', () => {
const args = ['node', 'worker-service.cjs', '--daemon'];
const command = args[2];
expect(command).toBe('--daemon');
});
it('should default to daemon mode without command', () => {
const args = ['node', 'worker-service.cjs'];
const command = args[2]; // undefined
// Default case in switch handles undefined by running as daemon
expect(command).toBeUndefined();
// 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
});
});