const fs = require('node:fs'); const path = require('node:path'); function emptyState() { return { version: 1, jobs: {} }; } function readState(filePath) { try { const state = JSON.parse(fs.readFileSync(filePath, 'utf8')); if (!state || typeof state !== 'object' || !state.jobs || typeof state.jobs !== 'object') return emptyState(); return { version: 1, jobs: state.jobs }; } catch { return emptyState(); } } function writeState(filePath, state) { fs.mkdirSync(path.dirname(filePath), { recursive: true }); const temporaryPath = `${filePath}.tmp-${process.pid}`; fs.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 }); fs.renameSync(temporaryPath, filePath); } function normaliseJob(job) { if (!job || !String(job.promptId || '').trim()) return null; return { promptId: String(job.promptId), title: String(job.title || 'Untitled job'), status: String(job.status || 'unknown'), queuedAt: job.queuedAt ?? null, completedAt: job.completedAt ?? null, durationMs: job.durationMs ?? null, outputCount: Number(job.outputCount) || 0, models: Array.isArray(job.models) ? job.models.map((model) => ({ nodeId: String(model?.nodeId || ''), type: String(model?.type || 'model'), name: String(model?.name || '').trim(), })).filter((model) => model.name).filter((model, index, all) => all.findIndex((item) => item.name === model.name) === index) : [], }; } function createJobStore(filePath) { const target = filePath || process.env.JOB_STORE_PATH || path.join(__dirname, 'data', 'job-history.json'); function sync(jobs) { const state = readState(target); const now = Date.now(); let changed = false; for (const candidate of jobs || []) { const job = normaliseJob(candidate); if (!job) continue; const existing = state.jobs[job.promptId]; const next = { ...(existing || {}), ...job, firstSeenAt: existing?.firstSeenAt || now }; if (JSON.stringify(existing) !== JSON.stringify(next)) { next.lastSeenAt = now; state.jobs[job.promptId] = next; changed = true; } } if (changed) writeState(target, state); return { changed, jobCount: Object.keys(state.jobs).length }; } function stats() { const state = readState(target); const counts = new Map(); for (const job of Object.values(state.jobs)) { for (const model of job.models || []) { const current = counts.get(model.name) || { name: model.name, jobCount: 0 }; current.jobCount += 1; counts.set(model.name, current); } } const models = [...counts.values()].sort((a, b) => b.jobCount - a.jobCount || a.name.localeCompare(b.name)); return { totalJobs: Object.keys(state.jobs).length, totalModels: models.length, models }; } return { sync, stats, path: target }; } module.exports = { createJobStore };