import * as fs from 'fs/promises'; import * as path from 'path'; import dotenv from 'dotenv'; // Load environment variables to get the context directory path dotenv.config(); const DEFAULT_CONTEXT_DIR = './lamplighter_context'; const LOG_FILE_NAME = 'history_log.md'; export class HistoryLogger { private logFilePath: string; constructor() { const contextDir = process.env.LAMPLIGHTER_CONTEXT_DIR || DEFAULT_CONTEXT_DIR; // Ensure the context directory exists, create if not // Note: fs.mkdir with recursive: true is idempotent (doesn't throw if dir exists) fs.mkdir(contextDir, { recursive: true }) .catch(err => console.error(`[HistoryLogger] Error creating context directory ${contextDir}:`, err)); this.logFilePath = path.join(contextDir, LOG_FILE_NAME); console.log(`[HistoryLogger] Initialized. Logging to: ${this.logFilePath}`); } private formatTimestamp(date: Date): string { const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); const hours = date.getHours().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0'); const seconds = date.getSeconds().toString().padStart(2, '0'); return `[${year}-${month}-${day} ${hours}:${minutes}:${seconds}]`; } async log(message: string): Promise { const timestamp = this.formatTimestamp(new Date()); const logEntry = `${timestamp} - ${message}\n`; try { await fs.appendFile(this.logFilePath, logEntry, 'utf-8'); } catch (error) { console.error(`[HistoryLogger] Failed to append to log file ${this.logFilePath}:`, error); // Decide if we should throw, retry, or just log the error // For now, just logging the error. } } }