'use strict'; const fs=require('node:fs'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'); const fail=message=>Object.assign(new Error(message),{status:400}); function redact(value,secrets=[],limit=4096){limit=Math.min(1024*1024,Math.max(1,limit));let text=String(value??'').slice(0,Math.max(32768,limit));for(const secret of secrets)if(typeof secret==='string'&&secret.length)text=text.split(secret).join('[REDACTED]');return text.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,'[REDACTED]').replace(/\b(?:Bearer|Basic)\s+[^\s,;]+/gi,'[REDACTED]').replace(/\b(?:api[_-]?key|token|password|secret|authorization|cookie)["']?\s*[:=]\s*(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;]+)/gi,'[REDACTED]').replace(/https?:\/\/[^\s/@:]+:[^\s/@]+@/gi,'https://[REDACTED]@').slice(0,limit);} class OperationJournal{ constructor({file,secrets=[]}){if(!path.isAbsolute(file))throw fail('Journal path must be absolute');fs.mkdirSync(path.dirname(file),{recursive:true});this.secrets=[...secrets];this.db=new DatabaseSync(file);this.db.exec(`PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS operation_events(id INTEGER PRIMARY KEY AUTOINCREMENT,operation_id TEXT NOT NULL,actor TEXT NOT NULL,created_at TEXT NOT NULL,payload TEXT NOT NULL);CREATE INDEX IF NOT EXISTS operation_actor ON operation_events(actor,id);CREATE TRIGGER IF NOT EXISTS immutable_operation_update BEFORE UPDATE ON operation_events BEGIN SELECT RAISE(ABORT,'append-only journal'); END;CREATE TRIGGER IF NOT EXISTS immutable_operation_delete BEFORE DELETE ON operation_events BEGIN SELECT RAISE(ABORT,'append-only journal'); END;`);} append(event){if(!event||typeof event.actor!=='string'||!event.actor||event.actor.length>128||typeof event.operationId!=='string'||!/^[\w-]{1,128}$/.test(event.operationId))throw fail('Invalid operation identity');const payload={operationId:event.operationId,actor:event.actor,createdAt:new Date().toISOString()};for(const key of ['step','status','previousCommit','resultCommit','testOutcome','recovery','detail','branch'])if(event[key]!==undefined)payload[key]=redact(event[key],this.secrets);const result=this.db.prepare('INSERT INTO operation_events(operation_id,actor,created_at,payload) VALUES(?,?,?,?)').run(event.operationId,event.actor,payload.createdAt,JSON.stringify(payload));return {id:Number(result.lastInsertRowid),...payload};} list({actor,isAdmin=false,operationId,limit=100,beforeId}={}){if(typeof actor!=='string'||!actor)throw fail('Actor required');limit=Math.min(200,Math.max(1,Number.isInteger(limit)?limit:100));if(beforeId!==undefined&&(!Number.isSafeInteger(beforeId)||beforeId<=0))throw fail('Invalid history cursor');const conditions=[],args=[];if(beforeId!==undefined){conditions.push('id({id:row.id,...JSON.parse(row.payload)}));} // Invoke once during host startup, before accepting any new operations. recoverRunning(){const rows=this.db.prepare('SELECT payload FROM operation_events WHERE id IN (SELECT MAX(id) FROM operation_events GROUP BY operation_id)').all();let count=0;for(const row of rows){const event=JSON.parse(row.payload);if(event.status==='running'){this.append({...event,step:'restart_recovery',status:'needs_review',testOutcome:'unknown',recovery:'manual_review',detail:'Process restarted; subprocess outcome and isolated files require inspection.'});count++;}}return count;} close(){this.db.close();} } module.exports={OperationJournal,redact};