import { app } from 'electron' import { join } from 'path' import { readFileSync, writeFileSync, existsSync } from 'fs' import type { ErrorLogEntry } from '@shared/ipc' import { isValidErrorLogEntry } from './validation' // Plain JSON in userData, same shape as history.ts. Persisted so a failure // report survives the queue item being cleared (Seal's "debug report"). const MAX_ENTRIES = 200 function errorLogFile(): string { return join(app.getPath('userData'), 'errorlog.json') } // Per-entry validation (isValidErrorLogEntry, in validation.ts) so a hand-edited // or corrupted errorlog.json can't feed the UI entries with the wrong shape — // invalid rows are dropped. (audit S5) export function listErrorLog(): ErrorLogEntry[] { try { if (!existsSync(errorLogFile())) return [] const data = JSON.parse(readFileSync(errorLogFile(), 'utf8')) return Array.isArray(data) ? data.filter(isValidErrorLogEntry) : [] } catch { return [] } } function save(entries: ErrorLogEntry[]): void { try { writeFileSync(errorLogFile(), JSON.stringify(entries.slice(0, MAX_ENTRIES), null, 2)) } catch { /* best-effort; a read-only data dir just means no persisted error log */ } } export function addErrorLog(entry: ErrorLogEntry): ErrorLogEntry[] { const entries = [entry, ...listErrorLog()] save(entries) return entries } export function clearErrorLog(): ErrorLogEntry[] { save([]) return [] }