fix: Claude Code 2.1.1 compatibility + log-level audit + path validation fixes (#614)

* Refactor CLAUDE.md and related files for December 2025 updates

- Updated CLAUDE.md in src/services/worker with new entries for December 2025, including changes to Search.ts, GeminiAgent.ts, SDKAgent.ts, and SessionManager.ts.
- Revised CLAUDE.md in src/shared to reflect updates and new entries for December 2025, including paths.ts and worker-utils.ts.
- Modified hook-constants.ts to clarify exit codes and their behaviors.
- Added comprehensive hooks reference documentation for Claude Code, detailing usage, events, and examples.
- Created initial CLAUDE.md files in various directories to track recent activity.

* fix: Merge user-message-hook output into context-hook hookSpecificOutput

- Add footer message to additionalContext in context-hook.ts
- Remove user-message-hook from SessionStart hooks array
- Fixes issue where stderr+exit(1) approach was silently discarded

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

* Update logs and documentation for recent plugin and worker service changes

- Added detailed logs for worker service activities from Dec 10, 2025 to Jan 7, 2026, including initialization patterns, cleanup confirmations, and diagnostic logging.
- Updated plugin documentation with recent activities, including plugin synchronization and configuration changes from Dec 3, 2025 to Jan 7, 2026.
- Enhanced the context hook and worker service logs to reflect improvements and fixes in the plugin architecture.
- Documented the migration and verification processes for the Claude memory system and its integration with the marketplace.

* Refactor hooks architecture and remove deprecated user-message-hook

- Updated hook configurations in CLAUDE.md and hooks.json to reflect changes in session start behavior.
- Removed user-message-hook functionality as it is no longer utilized in Claude Code 2.1.0; context is now injected silently.
- Enhanced context-hook to handle session context injection without user-visible messages.
- Cleaned up documentation across multiple files to align with the new hook structure and removed references to obsolete hooks.
- Adjusted timing and command execution for hooks to improve performance and reliability.

* fix: Address PR #610 review issues

- Replace USER_MESSAGE_ONLY test with BLOCKING_ERROR test in hook-constants.test.ts
- Standardize Claude Code 2.1.0 note wording across all three documentation files
- Exclude deprecated user-message-hook.ts from logger-usage-standards test

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

* fix: Remove hardcoded fake token counts from context injection

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

* Address PR #610 review issues by fixing test files, standardizing documentation notes, and verifying code quality improvements.

* fix: Add path validation to CLAUDE.md distribution to prevent invalid directory creation

- Add isValidPathForClaudeMd() function to reject invalid paths:
  - Tilde paths (~) that Node.js doesn't expand
  - URLs (http://, https://)
  - Paths with spaces (likely command text or PR references)
  - Paths with # (GitHub issue/PR references)
  - Relative paths that escape project boundary

- Integrate validation in updateFolderClaudeMdFiles loop
- Add 6 unit tests for path validation
- Update .gitignore to prevent accidental commit of malformed directories
- Clean up existing invalid directories (~/, PR #610..., git diff..., https:)

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

* fix: Implement path validation in CLAUDE.md generation to prevent invalid directory creation

- Added `isValidPathForClaudeMd()` function to validate file paths in `src/utils/claude-md-utils.ts`.
- Integrated path validation in `updateFolderClaudeMdFiles` to skip invalid paths.
- Added 6 new unit tests in `tests/utils/claude-md-utils.test.ts` to cover various rejection cases.
- Updated `.gitignore` to prevent tracking of invalid directories.
- Cleaned up existing invalid directories in the repository.

* feat: Promote critical WARN logs to ERROR level across codebase

Comprehensive log-level audit promoting 38+ WARN messages to ERROR for
improved debugging and incident response:

- Parser: observation type errors, data contamination
- SDK/Agents: empty init responses (Gemini, OpenRouter)
- Worker/Queue: session recovery, auto-recovery failures
- Chroma: sync failures, search failures (now treated as critical)
- SQLite: search failures (primary data store)
- Session/Generator: failures, missing context
- Infrastructure: shutdown, process management failures
- File Operations: CLAUDE.md updates, config reads
- Branch Management: recovery checkout failures

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

* fix: Address PR #614 review issues

- Remove incorrectly tracked tilde-prefixed files from git
- Fix absolute path validation to check projectRoot boundaries
- Add test coverage for absolute path validation edge cases

Closes review issues:
- Issue 1: ~/ prefixed files removed from tracking
- Issue 3: Absolute paths now validated against projectRoot
- Issue 4: Added 3 new test cases for absolute path scenarios

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

* build assets and context

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Alex Newman
2026-01-07 23:34:20 -05:00
committed by GitHub
parent 687146ce53
commit 2659ec3231
98 changed files with 8927 additions and 3554 deletions
+45 -118
View File
@@ -3,131 +3,58 @@
<!-- This section is auto-generated by claude-mem. Edit content outside the tags. -->
### Nov 10, 2025
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #6358 | 3:14 PM | 🔵 | SDK Agent Spatial Awareness Implementation | ~309 |
### Nov 21, 2025
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #13289 | 2:20 PM | 🟣 | Comprehensive Test Suite for Transcript Transformation | ~320 |
### Nov 23, 2025
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #14617 | 6:15 PM | 🟣 | Test Suite Successfully Passing - All 8 Tests Green | ~498 |
| #14615 | 6:14 PM | 🟣 | YAGNI-Focused Test Suite for Transcript Transformation | ~457 |
### Dec 5, 2025
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #20732 | 9:07 PM | 🔵 | Smart Install Version Marker Tests for Upgrade Detection | ~452 |
| #20399 | 7:17 PM | 🔵 | Smart install tests validate version tracking with backward compatibility | ~311 |
| #20392 | 7:15 PM | 🔵 | Memory tag stripping tests validate dual-tag system for JSON context filtering | ~404 |
| #20391 | " | 🔵 | User prompt tag stripping tests validate privacy controls for memory exclusion | ~182 |
### Jan 3, 2026
**logger-coverage.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36642 | 10:56 PM | 🔵 | Logger Coverage Test Requirements Analysis | ~483 |
| #36641 | " | 🔵 | Logger Coverage Test Suite Enforces Logging Standards | ~433 |
| #36616 | 10:42 PM | 🔵 | Logger Coverage Test Implementation Examined | ~540 |
**gemini_agent.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36639 | 10:55 PM | 🔵 | GeminiAgent Test Suite Structure | ~428 |
| #36637 | 10:47 PM | 🟣 | GeminiAgent Analysis Agent Running But Timed Out After 120 Seconds | ~521 |
| #36617 | 10:42 PM | 🔵 | GeminiAgent Test File Reveals Integration Requirements | ~506 |
**session_id_refactor.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36636 | 10:46 PM | 🟣 | Session ID Refactor Analysis Agent Completed Comprehensive Report | ~637 |
| #36615 | 10:42 PM | 🔵 | Session ID Refactor Test File Defines Expected Behavior | ~522 |
**session_store.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36635 | 10:46 PM | 🟣 | SessionStore Analysis Agent Completed Report Generation | ~545 |
| #36618 | 10:43 PM | 🔵 | SessionStore Test File Specifies Timestamp Override Feature | ~458 |
| #36485 | 9:12 PM | 🟣 | Prompts Module Test Suite Implemented | ~680 |
**session_id_usage_validation.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36625 | 10:44 PM | 🔵 | Documentation and Code Reveal Placeholder Detection Pattern | ~583 |
| #36619 | 10:43 PM | 🔵 | Session ID Validation Test Architecture Examined | ~705 |
**worker-spawn.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36570 | 9:54 PM | 🟣 | ProcessManager Infrastructure Test Suite Created | ~535 |
| #36663 | 11:06 PM | | Third Validation Test Updated: Resume Safety Check Now Uses NULL Comparison | ~417 |
| #36662 | " | | Second Validation Test Updated: Post-Capture Check Now Uses NULL Comparison | ~418 |
| #36661 | 11:05 PM | | First Validation Test Updated: Placeholder Detection Now Checks for NULL | ~482 |
| #36660 | " | ✅ | Updated Session ID Usage Validation Test Header to Reflect NULL-Based Architecture | ~588 |
| #36659 | " | ✅ | Sixth Test Fix: Updated Multi-Observation Test to Use Memory Session ID | ~486 |
| #36658 | " | | Fifth Test Fix: Updated storeSummary Tests to Use Actual Memory Session ID After Capture | ~555 |
| #36657 | 11:04 PM | ✅ | Fourth Test Fix: Updated storeObservation Tests to Use Actual Memory Session ID After Capture | ~547 |
| #36656 | " | | Third Test Fix: Updated getSessionById Test to Expect NULL for Uncaptured Memory Session ID | ~436 |
| #36655 | " | | Second Test Fix: Updated updateMemorySessionId Test to Expect NULL Before Update | ~395 |
| #36654 | " | | First Test Fix: Updated Memory Session ID Initialization Test to Expect NULL | ~426 |
| #36650 | 11:02 PM | 🔵 | Phase 1 Analysis Reveals Implementation-Test Mismatch on NULL vs Placeholder Initialization | ~687 |
| #36648 | " | 🔵 | Session ID Refactor Test Suite Documents Database Migration 17 and Dual ID System | ~651 |
| #36647 | 11:01 PM | 🔵 | SessionStore Test Suite Validates Prompt Counting and Timestamp Override Features | ~506 |
| #36646 | " | 🔵 | Session ID Architecture Revealed Through Test File Analysis | ~611 |
### Jan 4, 2026
**gemini_agent.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36924 | 2:25 AM | | Merged fix/pr-538-followups branch into main with comprehensive updates | ~481 |
| #36908 | 2:01 AM | | Regression Tests Committed Successfully | ~418 |
| #36907 | " | | Regression Test Files Staged for Commit | ~317 |
| #36842 | 1:43 AM | 🔵 | Complete Test Framework and Pattern Documentation | ~670 |
| #36836 | 1:42 AM | 🔵 | GeminiAgent Test Coverage and Mocking Patterns | ~513 |
| #36751 | 12:32 AM | 🔵 | Gemini-Related Files Located Across Project | ~242 |
**session_store.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36840 | 1:43 AM | 🔵 | SessionStore Integration Test Pattern | ~444 |
### Jan 5, 2026
**sdk-agent-resume.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #38086 | 10:42 PM | ✅ | Merged PR with comprehensive CLAUDE.md documentation system | ~478 |
**CLAUDE.md**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #38082 | 10:13 PM | ✅ | Merge Conflict Resolution - Kept Feature Branch Versions | ~431 |
**gemini_agent.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37819 | 6:44 PM | 🔄 | Replaced Module Mock with SpyOn Approach for SettingsDefaultsManager | ~354 |
| #37816 | " | 🔄 | Removed Module-Level Mocks from Gemini Test | ~347 |
| #37815 | " | 🔵 | Gemini Test Has Two Module-Level Mocks Defined Before Describe Block | ~375 |
| #37814 | " | 🔵 | Gemini Test Uses mock.restore() in afterEach Hook | ~319 |
| #37811 | 6:43 PM | 🔵 | SettingsDefaultsManager Tests Still Fail With Gemini Test Due to Mock | ~384 |
| #37809 | " | 🔴 | Logger Tests Now Pass When Run With Gemini Test | ~340 |
| #37800 | 6:41 PM | 🔴 | Fixed Incomplete SettingsDefaultsManager Mock in Gemini Agent Test | ~376 |
| #37799 | " | 🔵 | Gemini Test Uses mock.module to Override SettingsDefaultsManager | ~357 |
| #37798 | " | 🔵 | Gemini Agent Test Identified as Source of Module Corruption | ~351 |
**logger-coverage.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37797 | 6:41 PM | 🔴 | Logger Coverage Test Now Passes With Other Tests After Exclusion | ~311 |
| #37793 | 6:39 PM | 🔴 | Added SettingsDefaultsManager to Logger Coverage Test Exclusions | ~355 |
| #37792 | " | 🔴 | Logger Tests Pass When Run Together With Coverage Test | ~345 |
| #37790 | " | 🔵 | Logger Coverage Test Detects Console Usage in SettingsDefaultsManager | ~391 |
| #37755 | 6:22 PM | 🔵 | Score 3 Marginal Tests Verified: Mock-Heavy Tests Validate Structure, Not Behavior | ~580 |
| #37750 | 6:21 PM | 🔵 | Test Audit: logger-coverage.test.ts Enforces Logging Standards Across Codebase | ~629 |
| #37735 | 6:16 PM | ✅ | Test Suite Audit Report Generated: 41 Tests Scored and Analyzed | ~634 |
| #37629 | 5:36 PM | 🔵 | Comprehensive Testing Patterns Documentation Generated | ~629 |
| #37620 | 5:33 PM | 🔵 | Existing Logger Coverage Test Suite Structure | ~536 |
| #37617 | 5:32 PM | ⚖️ | PR #558 Review Requirements Categorized by Priority | ~637 |
**session_id_refactor.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37777 | 6:36 PM | 🔴 | Phase 1 Test Cleanup Completed - 6 Low-Quality Test Files Deleted | ~430 |
| #37764 | 6:32 PM | ✅ | Deleted 6 harmful test files causing mock pollution and testing zero runtime value | ~454 |
| #37756 | 6:22 PM | ⚖️ | Score 2 Weak Tests Verification Confirms Audit Findings | ~598 |
**cursor-hook-outputs.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37758 | 6:25 PM | ⚖️ | Integration Test Design for Four Critical Testing Gaps | ~729 |
**session_id_usage_validation.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37754 | 6:22 PM | 🔵 | Test Audit: session_id_usage_validation.test.ts Enforces Critical Session ID Architecture Invariants | ~826 |
**worker-spawn.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37752 | 6:21 PM | 🔵 | Test Audit: worker-spawn.test.ts Tests Configuration and Contracts Without Testing Actual Spawning | ~651 |
**cursor-context-update.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37706 | 6:10 PM | 🔵 | Test Audit: cursor-context-update.test.ts Validates Cursor Integration File Format | ~468 |
**validate_sql_update.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37705 | 6:10 PM | 🔵 | Test Audit: validate_sql_update.test.ts Validates SQL Refactor Correctness | ~374 |
| #36858 | 1:50 AM | 🟣 | Phase 1 Implementation Completed via Subagent | ~499 |
| #36854 | 1:49 AM | 🟣 | gemini-3-flash Model Tests Added to GeminiAgent Test Suite | ~470 |
| #36851 | " | 🔵 | GeminiAgent Test Structure Analyzed | ~565 |
</claude-mem-context>
+2 -2
View File
@@ -58,8 +58,8 @@ describe('hook-constants', () => {
expect(HOOK_EXIT_CODES.FAILURE).toBe(1);
});
it('should define USER_MESSAGE_ONLY exit code', () => {
expect(HOOK_EXIT_CODES.USER_MESSAGE_ONLY).toBe(3);
it('should define BLOCKING_ERROR exit code', () => {
expect(HOOK_EXIT_CODES.BLOCKING_ERROR).toBe(2);
});
});
+5 -43
View File
@@ -3,51 +3,13 @@
<!-- This section is auto-generated by claude-mem. Edit content outside the tags. -->
### Jan 3, 2026
**graceful-shutdown.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36574 | 9:55 PM | 🟣 | Phase 5 Infrastructure Tests Committed | ~357 |
| #36569 | 9:54 PM | 🟣 | GracefulShutdown Test Suite Created | ~457 |
**process-manager.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36571 | 9:54 PM | 🟣 | Phase 5 Infrastructure Tests Completed | ~504 |
| #36570 | " | 🟣 | ProcessManager Infrastructure Test Suite Created | ~535 |
**health-monitor.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36568 | 9:53 PM | 🟣 | HealthMonitor Test Suite Created for Phase 5 | ~437 |
### Jan 4, 2026
**wmic-parsing.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36924 | 2:25 AM | | Merged fix/pr-538-followups branch into main with comprehensive updates | ~481 |
| #36908 | 2:01 AM | | Regression Tests Committed Successfully | ~418 |
| #36907 | " | ✅ | Regression Test Files Staged for Commit | ~317 |
**process-manager.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36842 | 1:43 AM | 🔵 | Complete Test Framework and Pattern Documentation | ~670 |
| #36837 | 1:42 AM | 🔵 | ProcessManager Test Patterns with File System Operations | ~466 |
| #36779 | 12:44 AM | 🔵 | ProcessManager Windows PowerShell Functions Complete Analysis | ~550 |
### Jan 5, 2026
**wmic-parsing.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37735 | 6:16 PM | ✅ | Test Suite Audit Report Generated: 41 Tests Scored and Analyzed | ~634 |
**process-manager.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37629 | 5:36 PM | 🔵 | Comprehensive Testing Patterns Documentation Generated | ~629 |
| #37622 | 5:34 PM | 🔵 | Bun Test Pattern for File I/O and State Management | ~571 |
| #36870 | 1:54 AM | 🟣 | Phase 2 Implementation Completed via Subagent | ~572 |
| #36866 | 1:53 AM | 🔄 | WMIC Test Refactored to Use Direct Logic Testing | ~533 |
| #36865 | 1:52 AM | ✅ | WMIC Test File Updated with Improved Mock Implementation | ~370 |
| #36863 | 1:51 AM | 🟣 | WMIC Parsing Test File Created | ~581 |
| #36861 | " | 🔵 | Existing ProcessManager Test File Structure Analyzed | ~516 |
</claude-mem-context>
+309
View File
@@ -0,0 +1,309 @@
/**
* Log Level Audit Test
*
* This test scans all TypeScript files in src/ to find logger calls,
* extracts the message text, and groups them by log level for review.
*
* Purpose: Help identify misclassified log messages that should be at a different level.
*
* Log Level Guidelines:
* - ERROR/failure: Critical failures that require investigation (data loss, service down)
* - WARN: Non-critical issues with fallback behavior (degraded, but functional)
* - INFO: Normal operational events (session started, request processed)
* - DEBUG: Detailed diagnostic information (variable values, flow tracing)
*/
import { describe, it, expect } from 'bun:test';
import { readdir, readFile } from 'fs/promises';
import { join, relative } from 'path';
const PROJECT_ROOT = join(import.meta.dir, '..');
const SRC_DIR = join(PROJECT_ROOT, 'src');
interface LoggerCall {
file: string;
line: number;
level: string;
component: string;
message: string;
errorParam: string | null;
fullMatch: string;
}
/**
* Recursively find all TypeScript files in a directory
*/
async function findTypeScriptFiles(dir: string): Promise<string[]> {
const files: string[] = [];
const entries = await readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...(await findTypeScriptFiles(fullPath)));
} else if (entry.isFile() && /\.ts$/.test(entry.name) && !/\.d\.ts$/.test(entry.name)) {
files.push(fullPath);
}
}
return files;
}
/**
* Extract logger calls from file content
* Handles multiline calls and captures error parameter (4th arg)
*/
function extractLoggerCalls(content: string, filePath: string): LoggerCall[] {
const calls: LoggerCall[] = [];
const lines = content.split('\n');
const seenCalls = new Set<string>();
// Build line number index for position-to-line lookup
const lineStarts: number[] = [0];
for (let i = 0; i < content.length; i++) {
if (content[i] === '\n') {
lineStarts.push(i + 1);
}
}
function getLineNumber(pos: number): number {
for (let i = lineStarts.length - 1; i >= 0; i--) {
if (lineStarts[i] <= pos) return i + 1;
}
return 1;
}
// Pattern that matches logger calls across multiple lines
// Captures: method, component, message, and everything up to closing paren
// Uses [\s\S] instead of . to match newlines
const loggerPattern = /logger\.(error|warn|info|debug|failure|success|timing|dataIn|dataOut|happyPathError)\s*\(\s*['"]([^'"]+)['"][\s\S]*?\)/g;
let match: RegExpExecArray | null;
while ((match = loggerPattern.exec(content)) !== null) {
const fullMatch = match[0];
const method = match[1];
const component = match[2];
const lineNum = getLineNumber(match.index);
// Extract message (2nd string arg) - could be single, double, or template
const messageMatch = fullMatch.match(/['"][^'"]+['"]\s*,\s*(['"`])([\s\S]*?)\1/);
const message = messageMatch ? messageMatch[2] : '(message not captured)';
// Extract error parameter (4th arg) - look for "error as Error" or similar patterns
let errorParam: string | null = null;
const errorMatch = fullMatch.match(/,\s*(error|err|e)\s+as\s+Error\s*\)/i) ||
fullMatch.match(/,\s*(error|err|e)\s*\)/i) ||
fullMatch.match(/,\s*new\s+Error\s*\([^)]*\)\s*\)/i);
if (errorMatch) {
errorParam = errorMatch[0].replace(/^\s*,\s*/, '').replace(/\s*\)\s*$/, '');
}
const key = `${filePath}:${lineNum}:${method}:${message.substring(0, 50)}`;
if (!seenCalls.has(key)) {
seenCalls.add(key);
calls.push({
file: relative(PROJECT_ROOT, filePath),
line: lineNum,
level: normalizeLevel(method),
component,
message,
errorParam,
fullMatch: fullMatch.replace(/\s+/g, ' ').trim() // Normalize whitespace for display
});
}
}
return calls;
}
/**
* Normalize log level names to standard categories
*/
function normalizeLevel(method: string): string {
switch (method) {
case 'error':
case 'failure':
return 'ERROR';
case 'warn':
case 'happyPathError':
return 'WARN';
case 'info':
case 'success':
case 'timing':
case 'dataIn':
case 'dataOut':
return 'INFO';
case 'debug':
return 'DEBUG';
default:
return method.toUpperCase();
}
}
/**
* Generate formatted audit report
*/
function generateReport(calls: LoggerCall[]): string {
const byLevel: Record<string, LoggerCall[]> = {
'ERROR': [],
'WARN': [],
'INFO': [],
'DEBUG': []
};
for (const call of calls) {
if (byLevel[call.level]) {
byLevel[call.level].push(call);
}
}
const lines: string[] = [];
lines.push('\n=== LOG LEVEL AUDIT REPORT ===\n');
lines.push(`Total logger calls found: ${calls.length}\n`);
// ERROR level
lines.push('');
lines.push('ERROR (should be critical failures only):');
lines.push('─'.repeat(60));
if (byLevel['ERROR'].length === 0) {
lines.push(' (none found)');
} else {
for (const call of byLevel['ERROR'].sort((a, b) => a.file.localeCompare(b.file))) {
lines.push(` ${call.file}:${call.line} [${call.component}]`);
lines.push(` message: "${formatMessage(call.message)}"`);
if (call.errorParam) {
lines.push(` error: ${call.errorParam}`);
}
lines.push(` full: ${call.fullMatch}`);
lines.push('');
}
}
lines.push(` Count: ${byLevel['ERROR'].length}`);
// WARN level
lines.push('');
lines.push('WARN (should be non-critical, has fallback):');
lines.push('─'.repeat(60));
if (byLevel['WARN'].length === 0) {
lines.push(' (none found)');
} else {
for (const call of byLevel['WARN'].sort((a, b) => a.file.localeCompare(b.file))) {
lines.push(` ${call.file}:${call.line} [${call.component}]`);
lines.push(` message: "${formatMessage(call.message)}"`);
if (call.errorParam) {
lines.push(` error: ${call.errorParam}`);
}
lines.push(` full: ${call.fullMatch}`);
lines.push('');
}
}
lines.push(` Count: ${byLevel['WARN'].length}`);
// INFO level
lines.push('');
lines.push('INFO (informational):');
lines.push('─'.repeat(60));
if (byLevel['INFO'].length === 0) {
lines.push(' (none found)');
} else {
for (const call of byLevel['INFO'].sort((a, b) => a.file.localeCompare(b.file))) {
lines.push(` ${call.file}:${call.line} [${call.component}]`);
lines.push(` message: "${formatMessage(call.message)}"`);
if (call.errorParam) {
lines.push(` error: ${call.errorParam}`);
}
lines.push(` full: ${call.fullMatch}`);
lines.push('');
}
}
lines.push(` Count: ${byLevel['INFO'].length}`);
// DEBUG level
lines.push('');
lines.push('DEBUG (detailed diagnostics):');
lines.push('─'.repeat(60));
if (byLevel['DEBUG'].length === 0) {
lines.push(' (none found)');
} else {
for (const call of byLevel['DEBUG'].sort((a, b) => a.file.localeCompare(b.file))) {
lines.push(` ${call.file}:${call.line} [${call.component}]`);
lines.push(` message: "${formatMessage(call.message)}"`);
if (call.errorParam) {
lines.push(` error: ${call.errorParam}`);
}
lines.push(` full: ${call.fullMatch}`);
lines.push('');
}
}
lines.push(` Count: ${byLevel['DEBUG'].length}`);
// Summary
lines.push('');
lines.push('=== SUMMARY ===');
lines.push(` ERROR: ${byLevel['ERROR'].length}`);
lines.push(` WARN: ${byLevel['WARN'].length}`);
lines.push(` INFO: ${byLevel['INFO'].length}`);
lines.push(` DEBUG: ${byLevel['DEBUG'].length}`);
lines.push(` TOTAL: ${calls.length}`);
lines.push('');
return lines.join('\n');
}
/**
* Format message for display - NO TRUNCATION
*/
function formatMessage(message: string): string {
return message;
}
describe('Log Level Audit', () => {
let allCalls: LoggerCall[] = [];
it('should scan all TypeScript files and extract logger calls', async () => {
const files = await findTypeScriptFiles(SRC_DIR);
expect(files.length).toBeGreaterThan(0);
for (const file of files) {
const content = await readFile(file, 'utf-8');
const calls = extractLoggerCalls(content, file);
allCalls.push(...calls);
}
expect(allCalls.length).toBeGreaterThan(0);
});
it('should generate audit report for log level review', () => {
const report = generateReport(allCalls);
console.log(report);
// This test always passes - it's for generating a review report
expect(true).toBe(true);
});
it('should have summary statistics', () => {
const byLevel: Record<string, number> = {
'ERROR': 0,
'WARN': 0,
'INFO': 0,
'DEBUG': 0
};
for (const call of allCalls) {
if (byLevel[call.level] !== undefined) {
byLevel[call.level]++;
}
}
console.log('\n📊 Log Level Distribution:');
console.log(` ERROR: ${byLevel['ERROR']} (${((byLevel['ERROR'] / allCalls.length) * 100).toFixed(1)}%)`);
console.log(` WARN: ${byLevel['WARN']} (${((byLevel['WARN'] / allCalls.length) * 100).toFixed(1)}%)`);
console.log(` INFO: ${byLevel['INFO']} (${((byLevel['INFO'] / allCalls.length) * 100).toFixed(1)}%)`);
console.log(` DEBUG: ${byLevel['DEBUG']} (${((byLevel['DEBUG'] / allCalls.length) * 100).toFixed(1)}%)`);
// Log distribution health check - not a hard failure, just informational
// A healthy codebase typically has: DEBUG > INFO > WARN > ERROR
expect(allCalls.length).toBeGreaterThan(0);
});
});
+1
View File
@@ -34,6 +34,7 @@ const EXCLUDED_PATTERNS = [
/worker-service\.ts$/, // CLI entry point with interactive setup wizard (console.log for user prompts)
/integrations\/.*Installer\.ts$/, // CLI installer commands (console.log for interactive installation output)
/SettingsDefaultsManager\.ts$/, // Must use console.log to avoid circular dependency with logger
/user-message-hook\.ts$/, // Deprecated - kept for reference only, not registered in hooks.json
];
// Files that should always use logger (core business logic)
+1 -32
View File
@@ -3,36 +3,5 @@
<!-- This section is auto-generated by claude-mem. Edit content outside the tags. -->
### Jan 5, 2026
**claude-md-utils.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #38086 | 10:42 PM | ✅ | Merged PR with comprehensive CLAUDE.md documentation system | ~478 |
| #38047 | 9:45 PM | 🔴 | PR #556 Review Items - Worker Host Configuration and Path Resolution | ~389 |
| #38025 | 9:15 PM | 🔴 | Fixed PR #556 review items and committed changes | ~344 |
| #38024 | " | ✅ | Git status shows modified source files and auto-updated CLAUDE.md files | ~295 |
| #38022 | " | ✅ | Phase 3 complete: Worktree detection test coverage verified by agent | ~391 |
| #38021 | " | 🔵 | Test suite expanded with additional projectRoot edge case tests | ~389 |
| #38020 | 9:14 PM | ✅ | All 27 tests passing in claude-md-utils test suite | ~237 |
| #38019 | " | ✅ | Test suite passed for claude-md-utils.ts with all 27 tests green | ~306 |
| #38018 | " | 🟣 | Added comprehensive test coverage for worktree detection and projectRoot path resolution | ~450 |
| #38017 | " | ✅ | Verified existing claude-md-utils.test.ts passes with 27 tests | ~244 |
| #38016 | 9:13 PM | 🔵 | Existing test suite for claude-md-utils.ts with projectRoot tests already present | ~426 |
| #37977 | 8:33 PM | 🔵 | All 23 tests pass for claude-md-utils module | ~209 |
**logger-format-tool.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37809 | 6:43 PM | 🔴 | Logger Tests Now Pass When Run With Gemini Test | ~340 |
| #37797 | 6:41 PM | 🔴 | Logger Coverage Test Now Passes With Other Tests After Exclusion | ~311 |
| #37796 | 6:40 PM | 🔴 | Utils and Shared Tests Pass When Run Together | ~342 |
| #37792 | 6:39 PM | 🔴 | Logger Tests Pass When Run Together With Coverage Test | ~345 |
| #37789 | 6:38 PM | 🔴 | Logger FormatTool Tests Pass When Run In Isolation | ~359 |
| #37777 | 6:36 PM | 🔴 | Phase 1 Test Cleanup Completed - 6 Low-Quality Test Files Deleted | ~430 |
| #37769 | 6:34 PM | 🔵 | Logger-format-tool test file contains 81 comprehensive tests for non-existent logger.formatTool method | ~487 |
| #37655 | 5:51 PM | 🔵 | Logger formatTool test imports logger directly creating test-time circular dependency exposure | ~392 |
| #37642 | 5:41 PM | 🟣 | Second Task Agent Independently Created and Verified FormatTool Tests | ~544 |
| #37638 | 5:40 PM | 🟣 | FormatTool Test Suite Successfully Passes All 56 Tests | ~515 |
| #37635 | 5:39 PM | 🟣 | Created Comprehensive FormatTool Test Suite | ~619 |
*No recent activity*
</claude-mem-context>
+153 -4
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, mock, afterEach, beforeEach } from 'bun:test';
import { mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'fs';
import { join } from 'path';
import path, { join } from 'path';
import { tmpdir } from 'os';
// Mock logger BEFORE imports (required pattern)
@@ -322,7 +322,7 @@ describe('updateFolderClaudeMdFiles', () => {
expect(callUrl).toContain(encodeURIComponent('/home/user/my-project/src/utils'));
});
it('should not modify absolute paths even with projectRoot', async () => {
it('should accept absolute paths within projectRoot and use them directly', async () => {
const folderPath = join(tempDir, 'absolute-path-test');
const filePath = join(folderPath, 'file.ts');
@@ -339,10 +339,10 @@ describe('updateFolderClaudeMdFiles', () => {
global.fetch = fetchMock;
await updateFolderClaudeMdFiles(
[filePath], // absolute path
[filePath], // absolute path within tempDir
'test-project',
37777,
'/home/user/my-project' // projectRoot should be ignored
tempDir // projectRoot matches the absolute path's root
);
// Should call API with the original absolute path's folder
@@ -485,3 +485,152 @@ describe('updateFolderClaudeMdFiles', () => {
expect(callUrl).toContain(encodeURIComponent('/home/user/project/src'));
});
});
describe('path validation in updateFolderClaudeMdFiles', () => {
it('should reject tilde paths', async () => {
const fetchMock = mock(() => Promise.resolve({ ok: true } as Response));
global.fetch = fetchMock;
await updateFolderClaudeMdFiles(
['~/.claude-mem/logs/worker.log'],
'test-project',
37777,
tempDir
);
expect(fetchMock).not.toHaveBeenCalled();
});
it('should reject URLs', async () => {
const fetchMock = mock(() => Promise.resolve({ ok: true } as Response));
global.fetch = fetchMock;
await updateFolderClaudeMdFiles(
['https://example.com/file.ts'],
'test-project',
37777,
tempDir
);
expect(fetchMock).not.toHaveBeenCalled();
});
it('should reject paths with spaces', async () => {
const fetchMock = mock(() => Promise.resolve({ ok: true } as Response));
global.fetch = fetchMock;
await updateFolderClaudeMdFiles(
['PR #610 on thedotmack/CLAUDE.md'],
'test-project',
37777,
tempDir
);
expect(fetchMock).not.toHaveBeenCalled();
});
it('should reject paths with hash symbols', async () => {
const fetchMock = mock(() => Promise.resolve({ ok: true } as Response));
global.fetch = fetchMock;
await updateFolderClaudeMdFiles(
['issue#123/file.ts'],
'test-project',
37777,
tempDir
);
expect(fetchMock).not.toHaveBeenCalled();
});
it('should reject path traversal outside project', async () => {
const fetchMock = mock(() => Promise.resolve({ ok: true } as Response));
global.fetch = fetchMock;
await updateFolderClaudeMdFiles(
['../../../etc/passwd'],
'test-project',
37777,
tempDir
);
expect(fetchMock).not.toHaveBeenCalled();
});
it('should reject absolute paths outside project root', async () => {
const fetchMock = mock(() => Promise.resolve({ ok: true } as Response));
global.fetch = fetchMock;
await updateFolderClaudeMdFiles(
['/etc/passwd'],
'test-project',
37777,
tempDir
);
expect(fetchMock).not.toHaveBeenCalled();
});
it('should accept absolute paths within project root', async () => {
const apiResponse = {
content: [{ text: '| #123 | 4:30 PM | 🔵 | Test | ~100 |' }]
};
const fetchMock = mock(() => Promise.resolve({
ok: true,
json: () => Promise.resolve(apiResponse)
} as Response));
global.fetch = fetchMock;
// Create an absolute path within the temp directory
const absolutePathInProject = path.join(tempDir, 'src', 'utils', 'file.ts');
await updateFolderClaudeMdFiles(
[absolutePathInProject],
'test-project',
37777,
tempDir
);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('should accept absolute paths when no projectRoot is provided', async () => {
const apiResponse = {
content: [{ text: '| #123 | 4:30 PM | 🔵 | Test | ~100 |' }]
};
const fetchMock = mock(() => Promise.resolve({
ok: true,
json: () => Promise.resolve(apiResponse)
} as Response));
global.fetch = fetchMock;
await updateFolderClaudeMdFiles(
['/home/user/valid/file.ts'],
'test-project',
37777
// No projectRoot provided
);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('should accept valid relative paths', async () => {
const apiResponse = {
content: [{ text: '| #123 | 4:30 PM | 🔵 | Test | ~100 |' }]
};
const fetchMock = mock(() => Promise.resolve({
ok: true,
json: () => Promise.resolve(apiResponse)
} as Response));
global.fetch = fetchMock;
await updateFolderClaudeMdFiles(
['src/utils/logger.ts'],
'test-project',
37777,
tempDir
);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});
+1 -45
View File
@@ -3,49 +3,5 @@
<!-- This section is auto-generated by claude-mem. Edit content outside the tags. -->
### Jan 3, 2026
**fallback-error-handler.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36522 | 9:34 PM | 🟣 | Phase 2 Worker Agent Tests Implemented | ~390 |
| #36525 | " | 🔵 | Test Import Strategy for Avoiding Module Side Effects | ~358 |
| #36518 | " | 🟣 | Phase 2 Test Suite Implementation Complete | ~348 |
| #36521 | " | ⚖️ | Test Import Strategy: Direct Imports Over Barrel Exports | ~321 |
| #36515 | 9:33 PM | 🟣 | Phase 2 Worker Agents Test Suite Implementation | ~422 |
### Jan 4, 2026
**observation-broadcaster.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #36842 | 1:43 AM | 🔵 | Complete Test Framework and Pattern Documentation | ~670 |
| #36834 | 1:41 AM | 🔵 | Bun Test Framework Pattern and Structure | ~418 |
### Jan 5, 2026
**CLAUDE.md**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #38078 | 9:54 PM | ✅ | CLAUDE.md Documentation Cleanup - 1,233 Lines Removed Across 18 Files | ~590 |
**response-processor.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37999 | 9:02 PM | 🔵 | getWorkerHost and getWorkerPort used in 18 files across codebase | ~282 |
| #37756 | 6:22 PM | ⚖️ | Score 2 Weak Tests Verification Confirms Audit Findings | ~598 |
| #37712 | 6:12 PM | 🔵 | Test Audit: response-processor.test.ts Has Heavy Mocking for XML Parsing and Database Operations | ~697 |
**observation-broadcaster.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37777 | 6:36 PM | 🔴 | Phase 1 Test Cleanup Completed - 6 Low-Quality Test Files Deleted | ~430 |
| #37764 | 6:32 PM | ✅ | Deleted 6 harmful test files causing mock pollution and testing zero runtime value | ~454 |
| #37755 | 6:22 PM | 🔵 | Score 3 Marginal Tests Verified: Mock-Heavy Tests Validate Structure, Not Behavior | ~580 |
| #37711 | 6:11 PM | 🔵 | Test Audit: observation-broadcaster.test.ts Validates SSE Broadcasting with Mock Workers | ~605 |
**fallback-error-handler.test.ts**
| ID | Time | T | Title | Read |
|----|------|---|-------|------|
| #37735 | 6:16 PM | ✅ | Test Suite Audit Report Generated: 41 Tests Scored and Analyzed | ~634 |
*No recent activity*
</claude-mem-context>