import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let CENTRAL;
function loadCentral(){
if(CENTRAL) return CENTRAL;
const jsonPath = path.join(__dirname,'risk-dictionary.json');
const raw = fs.readFileSync(jsonPath,'utf-8');
const arr = JSON.parse(raw);
CENTRAL = new Set(arr);
return CENTRAL;
}
export function classifyCommands({central=loadCentral(), frontmatterRisk=[], frontmatterSafe=[], extracted=[]}){
const risk = new Set();
const safe = new Set();
for(const cmd of extracted){
const key = String(cmd).toLowerCase();
if([...central].some(w=> key.includes(w))) risk.add(cmd);
else safe.add(cmd);
}
frontmatterRisk.forEach(r=> risk.add(r));
frontmatterSafe.forEach(s=> { if(!risk.has(s)) safe.add(s); });
return {
risk_ops: Array.from(risk).map(c=>({command:c, rollbackHint:'VERIFY_ROLLBACK_MANUALLY'})),
safe_ops: Array.from(safe)
};
}
// New simple API expected by indexer: classifyRisk(bodyText, frontmatter)
// Returns { risks, safeOps }
export function classifyRisk(body, frontmatter = {}) {
const central = loadCentral();
const fmRisks = Array.isArray(frontmatter.risks) ? frontmatter.risks : [];
const fmSafe = Array.isArray(frontmatter.safe_ops) ? frontmatter.safe_ops : [];
const text = body || '';
const lower = text.toLowerCase();
const detected = [];
for (const term of central) {
if (lower.includes(term.toLowerCase())) detected.push(term);
}
const risks = Array.from(new Set([...detected, ...fmRisks]));
const safeOps = fmSafe.filter(op => !risks.includes(op));
return { risks, safeOps };
}
export function riskDictionary(){ return loadCentral(); }