const crypto = require("crypto"); const fs = require("fs"); const path = require("path"); const STATUS_OK = "ok"; const STATUS_SUS = "sus"; const STATUS_INHERITED_SUS = "inherited-sus"; const VALID_STATUSES = new Set([STATUS_OK, STATUS_SUS, STATUS_INHERITED_SUS]); const SUS_RESULT = Symbol("optimus.sus-result"); function isPlainObject(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function overlaySettingsValue(base, overlay) { if (!isPlainObject(base) || !isPlainObject(overlay)) return overlay; const result = { ...base }; for (const [key, value] of Object.entries(overlay)) { result[key] = key in result ? overlaySettingsValue(result[key], value) : value; } return result; } function applySettingOverlay(settings, projectRoot, overlayPath) { const resolvedPath = path.isAbsolute(overlayPath) ? overlayPath : path.resolve(projectRoot, overlayPath); const overlay = JSON.parse(fs.readFileSync(resolvedPath, "utf8")); if (!isPlainObject(overlay)) throw new Error(`Setting overlay must contain an object: ${overlayPath}`); for (const [name, value] of Object.entries(overlay)) { settings.set(name, settings.has(name) ? overlaySettingsValue(settings.get(name), value) : value); } } function loadSettings(projectRoot, settingOverlays = []) { const settingsRoot = path.join(projectRoot, "settings"); if (!fs.existsSync(settingsRoot)) throw new Error(`No settings folder found in ${projectRoot}`); const settings = new Map(); for (const fileName of fs.readdirSync(settingsRoot)) { if (path.extname(fileName).toLowerCase() !== ".json") continue; const name = path.basename(fileName, path.extname(fileName)); const filePath = path.join(settingsRoot, fileName); settings.set(name, JSON.parse(fs.readFileSync(filePath, "utf8"))); } for (const overlayPath of settingOverlays) applySettingOverlay(settings, projectRoot, overlayPath); return settings; } function hashPayload(value) { const json = JSON.stringify(value); return crypto.createHash("sha256").update(json === undefined ? "undefined" : json).digest("hex"); } function getSourceHash(sources) { const sourceHash = {}; for (const [name, source] of Object.entries(sources)) { if (!source || typeof source !== "object" || !("hash" in source)) { throw new Error(`Source "${name}" must be a node with a hash`); } sourceHash[name] = source.hash; } return sourceHash; } function getSourceRef(sources) { const sourceRef = {}; for (const [name, source] of Object.entries(sources)) { if (source && typeof source === "object" && source.artifact) sourceRef[name] = source.artifact; } return sourceRef; } function statusOf(node) { if (!node || typeof node !== "object" || node.status === undefined) return STATUS_OK; if (!VALID_STATUSES.has(node.status)) throw new Error(`Unknown artifact status: ${JSON.stringify(node.status)}`); return node.status; } function inheritedStatus(sources = {}) { return Object.values(sources).some(source => statusOf(source) !== STATUS_OK) ? STATUS_INHERITED_SUS : STATUS_OK; } function sus(payload) { return { [SUS_RESULT]: true, payload }; } function unwrapResult(result) { return result && typeof result === "object" && result[SUS_RESULT] === true ? { payload: result.payload, localSus: true } : { payload: result, localSus: false }; } function buildNode(result, sources = {}) { const { payload, localSus } = unwrapResult(result); return { sourceHash: getSourceHash(sources), hash: hashPayload(payload), status: localSus ? STATUS_SUS : inheritedStatus(sources), payload, }; } function buildBinaryNode(filePath, sources = {}) { const bytes = fs.readFileSync(filePath); return { sourceHash: getSourceHash(sources), hash: crypto.createHash("sha256").update(bytes).digest("hex"), status: inheritedStatus(sources), payloadBin: filePath, }; } function ensureDir(filename) { fs.mkdirSync(path.dirname(filename), { recursive: true }); } function writeJsonAtomic(filename, value) { ensureDir(filename); const tempFile = `${filename}.${process.pid}.${crypto.randomUUID()}.tmp`; fs.writeFileSync(tempFile, JSON.stringify(value, null, 2) + "\n", "utf8"); try { fs.renameSync(tempFile, filename); } catch (error) { if (!fs.existsSync(filename)) throw error; fs.rmSync(filename, { force: true }); fs.renameSync(tempFile, filename); } } function readArtifact(filename) { if (!fs.existsSync(filename)) return null; try { return JSON.parse(fs.readFileSync(filename, "utf8")); } catch { return null; } } function sameSourceHash(node, sources = {}) { if (!node || typeof node !== "object" || !node.hash || !node.sourceHash) return false; const expected = getSourceHash(sources); const actualKeys = Object.keys(node.sourceHash).sort(); const expectedKeys = Object.keys(expected).sort(); return actualKeys.length === expectedKeys.length && expectedKeys.every((name, index) => name === actualKeys[index] && node.sourceHash[name] === expected[name]); } function reconcileArtifactStatus(filename, node, sources = {}) { if (!node || typeof node !== "object") return node; const current = statusOf(node); const expected = current === STATUS_SUS ? STATUS_SUS : inheritedStatus(sources); if (current === expected) return node; const updated = { ...node, status: expected }; writeJsonAtomic(filename, updated); return updated; } async function resolveArtifact(filename, sources, producer) { const existing = readArtifact(filename); if (existing && sameSourceHash(existing, sources)) return reconcileArtifactStatus(filename, existing, sources); const result = await producer(); const node = buildNode(result, sources); node.artifact = path.relative(process.cwd(), filename).replace(/\\/g, "/"); const sourceRef = getSourceRef(sources); if (Object.keys(sourceRef).length > 0) node.sourceRef = sourceRef; writeJsonAtomic(filename, node); return node; } function invalidateArtifact(filename) { if (!fs.existsSync(filename)) return false; fs.rmSync(filename, { recursive: true, force: true }); return true; } function fileNode(filename) { const bytes = fs.readFileSync(filename); const ref = path.relative(process.cwd(), filename).replace(/\\/g, "/"); return { artifact: ref, sourceHash: {}, hash: crypto.createHash("sha256").update(bytes).digest("hex"), status: STATUS_OK, payload: ref, }; } function codeNode(label, value) { const code = typeof value === "function" ? value.toString() : String(value); return buildNode({ label, code }); } function initialize(projectRoot = process.cwd(), options = {}) { const settingOverlays = options.settingOverlays || []; if (!Array.isArray(settingOverlays)) throw new Error("options.settingOverlays must be an array"); const settings = loadSettings(projectRoot, settingOverlays); const registry = new Map(); let artifactOutcome; let relitigateSus = false; const inspection = options.inspection || null; if (inspection && typeof inspection.visit !== "function") { throw new Error("Inspection requires a visit(filename) callback"); } function inspectVisit(filename) { if (inspection) inspection.visit(filename); } function requireCurrentArtifact(filename, isCurrent) { if (!inspection) return; if (!isCurrent) throw new Error(`Vacuum verification: missing or stale artifact: ${filename}`); inspectVisit(filename); } const presentation = settings.get("presentation") || {}; const showOnEnsure = presentation.showOnEnsure === true; const showOnBuild = presentation.showOnBuild !== false; function displayArtifactLabel(value) { if (!value) return "artifact"; if (!path.isAbsolute(value)) return String(value); const relative = path.relative(projectRoot, value).replace(/\\/g, "/"); return relative || path.basename(value); } function reportEnsure(value) { if (showOnEnsure) console.log(`Ensuring artifact: ${displayArtifactLabel(value)}`); } function reportBuild(value) { // Diagnostic-only in normal runs; fail closed if a custom transformer // tries to build while the vacuum is inspecting stored results. if (inspection) throw new Error(`Vacuum verification: rebuild attempted: ${displayArtifactLabel(value)}`); if (showOnBuild) console.log(`Building artifact: ${displayArtifactLabel(value)}`); } async function projectResolveArtifact(filename, sources, producer) { reportEnsure(filename); const existing = readArtifact(filename); if (inspection) { const matching = existing && sameSourceHash(existing, sources); if (!matching) throw new Error(`Vacuum verification: missing or stale artifact: ${displayArtifactLabel(filename)}`); const expected = statusOf(existing) === STATUS_SUS ? STATUS_SUS : inheritedStatus(sources); if (statusOf(existing) !== expected) { throw new Error(`Vacuum verification: status not reconciled: ${displayArtifactLabel(filename)}`); } inspectVisit(filename); return existing; } if (existing && sameSourceHash(existing, sources)) { const reconciled = reconcileArtifactStatus(filename, existing, sources); if (!(relitigateSus && statusOf(reconciled) === STATUS_SUS)) return reconciled; } reportBuild(filename); const result = await producer(); const node = buildNode(result, sources); node.artifact = path.relative(process.cwd(), filename).replace(/\\/g, "/"); const sourceRef = getSourceRef(sources); if (Object.keys(sourceRef).length > 0) node.sourceRef = sourceRef; writeJsonAtomic(filename, node); return node; } const utils = { loadModule(name) { const entry = registry.get(name); if (!entry) throw new Error(`Unknown module: ${name}`); if (entry.module) return entry.module; if (entry.initializing) throw new Error(`Circular module initialization involving: ${name}`); entry.initializing = true; try { const initialized = entry.init(utils); if (!initialized || (typeof initialized !== "object" && typeof initialized !== "function")) { throw new Error(`Module "${name}" initializer must return a module object or function`); } entry.module = initialized; return entry.module; } finally { entry.initializing = false; } }, getSettings(name) { if (!settings.has(name)) throw new Error(`Unknown settings: ${name}`); return settings.get(name); }, hashPayload, buildNode, buildBinaryNode, resolveArtifact: projectResolveArtifact, readArtifact(filename) { const result = readArtifact(filename); if (inspection && result) inspectVisit(filename); return result; }, sameSourceHash, statusOf, sus, reconcileArtifactStatus(filename, node, sources = {}) { if (inspection) { const current = statusOf(node); const expected = current === STATUS_SUS ? STATUS_SUS : inheritedStatus(sources); if (current !== expected) throw new Error(`Vacuum verification: status not reconciled: ${displayArtifactLabel(filename)}`); inspectVisit(filename); return node; } return reconcileArtifactStatus(filename, node, sources); }, requireCurrentArtifact, shouldRelitigateSus(node) { return relitigateSus && statusOf(node) === STATUS_SUS; }, invalidateArtifact(filename) { if (inspection) throw new Error(`Vacuum verification: invalidation attempted: ${displayArtifactLabel(filename)}`); return invalidateArtifact(filename); }, fileNode(filename) { const result = fileNode(filename); if (inspection) inspectVisit(filename); return result; }, codeNode, // UI/diagnostic reporting only. These must never participate in // artifact identity, validity, ancestry, or dependency resolution. reportEnsure, reportBuild, setArtifactOutcome(value) { artifactOutcome = `${value ?? ""}`.trim() || undefined; }, }; const modules = utils.getSettings("modules"); if (!modules || typeof modules !== "object" || Array.isArray(modules)) throw new Error("settings/modules.json must contain an object"); for (const [name, modulePath] of Object.entries(modules)) { const resolvedPath = path.resolve(projectRoot, modulePath); const init = require(resolvedPath); if (typeof init !== "function") throw new Error(`Module "${name}" must export an initializer function: ${modulePath}`); registry.set(name, { init, module: null, initializing: false }); } for (const name of registry.keys()) utils.loadModule(name); function buildArtifact(name, options = {}) { if (!options || typeof options !== "object" || Array.isArray(options)) throw new Error("buildArtifact options must be an object"); const artifacts = utils.getSettings("artifacts"); const artifact = artifacts[name]; if (!artifact) throw new Error(`Unknown artifact: ${name}`); if (!artifact.module) throw new Error(`Artifact "${name}" is missing module`); if (!artifact.builder) throw new Error(`Artifact "${name}" is missing builder`); const module = utils.loadModule(artifact.module); const builder = module[artifact.builder]; if (typeof builder !== "function") { throw new Error(`Artifact "${name}" builder not found: ${artifact.module}.${artifact.builder}`); } const params = artifact.params === undefined ? [] : artifact.params; if (!Array.isArray(params)) throw new Error(`Artifact "${name}" params must be an array`); const previousRelitigateSus = relitigateSus; relitigateSus = previousRelitigateSus || options.relitigateSus === true; artifactOutcome = undefined; reportEnsure(name); const restore = () => { relitigateSus = previousRelitigateSus; }; try { const result = builder(...params); if (result && typeof result.then === "function") { return result.then(value => { if (showOnEnsure && artifactOutcome) console.log(` ${artifactOutcome}`); artifactOutcome = undefined; restore(); return value; }, error => { console.error(`Artifact failed: ${name}`); artifactOutcome = undefined; restore(); throw error; }); } if (showOnEnsure && artifactOutcome) console.log(` ${artifactOutcome}`); artifactOutcome = undefined; restore(); return result; } catch (error) { console.error(`Artifact failed: ${name}`); artifactOutcome = undefined; restore(); throw error; } } async function buildAll(options = {}) { const artifacts = utils.getSettings("artifacts"); for (const name of Object.keys(artifacts)) await buildArtifact(name, options); } return { utils, loadModule: utils.loadModule, getSettings: utils.getSettings, hashPayload, buildNode, buildBinaryNode, resolveArtifact: projectResolveArtifact, readArtifact, sameSourceHash, statusOf, sus, reconcileArtifactStatus, invalidateArtifact, fileNode, codeNode, buildArtifact, buildAll, modules: [...registry.keys()], }; } module.exports = { initialize, hashPayload, buildNode, buildBinaryNode, resolveArtifact, readArtifact, sameSourceHash, statusOf, sus, reconcileArtifactStatus, invalidateArtifact, fileNode, codeNode, };