Files
2026-10-26 22:21:04 -05:00

271 lines
14 KiB
JavaScript

"use strict";
// Maintenance-only. No static dependency graph or persistent runtime cache:
// ask every configured target to ensure its work, with all writes prohibited,
// then inventory files not reached by the active pull graph.
const fs = require("node:fs");
const path = require("node:path");
const crypto = require("node:crypto");
const http = require("node:http");
const https = require("node:https");
const net = require("node:net");
const tls = require("node:tls");
const childProcess = require("node:child_process");
const { initialize, hashPayload } = require("./index");
const SCHEMA = "optimus-vacuum-v1";
function sha256(bytes) { return crypto.createHash("sha256").update(bytes).digest("hex"); }
function inside(root, file) {
const relative = path.relative(root, path.resolve(file));
return relative && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
}
function posix(relative) { return relative.split(path.sep).join("/"); }
function* filesUnder(dir) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a,b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
const filename = path.join(dir, entry.name);
if (entry.isSymbolicLink()) throw new Error(`Vacuum refuses symlink under artifacts: ${filename}`);
if (entry.isDirectory()) yield* filesUnder(filename);
else if (entry.isFile()) yield filename;
else throw new Error(`Vacuum refuses special filesystem entry: ${filename}`);
}
}
// Builders may implement custom freshness, but must never write or contact a
// provider during verification. Optimus checks its own lifecycle first; these
// guards reject accidental project-owned side effects and child processes.
async function withoutSideEffects(work, onRead = () => {}) {
const restores = [];
function block(object, name) {
const original = object[name];
if (typeof original !== "function") return;
const descriptor = Object.getOwnPropertyDescriptor(object, name);
if (descriptor && !descriptor.writable && !descriptor.set) return;
object[name] = function blockedInVacuum() { throw new Error(`Vacuum verification forbids ${name}(); run npx optimus first`); };
restores.push(() => { object[name] = original; });
}
function guardedOpen(object, name, flagsAt) {
const original = object[name];
if (typeof original !== "function") return;
object[name] = function vacuumOpen(...args) {
const flag = args[flagsAt];
if (!(flag === "r" || flag === "rs" || flag === undefined)) {
throw new Error(`Vacuum verification forbids writable ${name}(${String(flag)})`);
}
return original.apply(this, args);
};
restores.push(() => { object[name] = original; });
}
const syncAndCallbackMutators = ["writeFile", "writeFileSync", "appendFile", "appendFileSync",
"rename", "renameSync", "rm", "rmSync", "rmdir", "rmdirSync", "unlink", "unlinkSync",
"mkdir", "mkdirSync", "copyFile", "copyFileSync", "cp", "cpSync", "truncate", "truncateSync",
"ftruncate", "ftruncateSync", "symlink", "symlinkSync", "link", "linkSync",
"chmod", "chmodSync", "chown", "chownSync", "utimes", "utimesSync",
"lutimes", "lutimesSync", "write", "writeSync", "writev", "writevSync", "createWriteStream"];
for (const name of syncAndCallbackMutators) block(fs, name);
const readFileSync = fs.readFileSync;
fs.readFileSync = function observedRead(filename, ...args) {
const contents = readFileSync.call(this, filename, ...args);
if (typeof filename === "string") onRead(filename);
return contents;
};
restores.push(() => { fs.readFileSync = readFileSync; });
guardedOpen(fs, "open", 1);
guardedOpen(fs, "openSync", 1);
for (const name of syncAndCallbackMutators) block(fs.promises, name);
const promiseReadFile = fs.promises.readFile;
fs.promises.readFile = async function observedPromiseRead(filename, ...args) {
const contents = await promiseReadFile.call(this, filename, ...args);
if (typeof filename === "string") onRead(filename);
return contents;
};
restores.push(() => { fs.promises.readFile = promiseReadFile; });
guardedOpen(fs.promises, "open", 1);
for (const name of ["request", "get"]) { block(http,name); block(https,name); }
for (const name of ["createConnection", "connect"]) block(net,name);
block(tls,"connect");
for (const name of ["spawn", "spawnSync", "exec", "execSync", "execFile", "execFileSync", "fork"]) block(childProcess,name);
if (typeof globalThis.fetch === "function") {
const oldFetch = globalThis.fetch;
globalThis.fetch = () => { throw new Error("Vacuum verification forbids network fetch()"); };
restores.push(() => { globalThis.fetch = oldFetch; });
}
try { return await work(); }
finally { for (const restore of restores.reverse()) restore(); }
}
function validateArtifactRoot(projectRoot) {
const root = path.join(projectRoot, "artifacts");
if (!fs.existsSync(root) || !fs.statSync(root).isDirectory() || fs.lstatSync(root).isSymbolicLink()) {
throw new Error(`Vacuum requires an ordinary artifacts directory: ${root}`);
}
return root;
}
async function traceCatalog(projectRoot, artifactRoot, settingOverlays = [], log = () => {}) {
const visited = new Set();
let observedReads = 0;
const mark = filename => {
if (inside(artifactRoot, filename)) {
observedReads++;
visited.add(posix(path.relative(projectRoot, path.resolve(filename))));
}
};
let targets;
await withoutSideEffects(async () => {
const engine = initialize(projectRoot, { settingOverlays, inspection: { visit: mark } });
targets = Object.keys(engine.getSettings("artifacts"));
if (targets.length === 0) throw new Error("Vacuum refuses an empty artifact catalog");
for (let i=0; i<targets.length; i++) {
log(`Verifying ${i+1}/${targets.length}: ${targets[i]}`);
const before = observedReads;
const result = await engine.buildArtifact(targets[i]);
// A target with neither a stored artifact nor a recursively used
// result is not evidence of a live dependency tree.
if (result && typeof result === "object" && typeof result.artifact === "string") {
const targetFile = path.resolve(projectRoot, result.artifact);
if (inside(artifactRoot, targetFile)) mark(targetFile);
}
if (observedReads === before) {
throw new Error(`Target ${targets[i]} did not ensure or read any persistent artifacts; cannot verify reachability`);
}
}
}, mark);
if (visited.size === 0) throw new Error("No persisted artifacts were traced; refusing to vacuum");
// Stored sourceRef handles dependencies that may have been loaded directly
// rather than explicitly ensured during this particular traversal.
const queue = [...visited];
const validated = new Set();
while (queue.length) {
const name = queue.pop();
if (validated.has(name)) continue;
validated.add(name);
const filename = path.join(projectRoot, name);
if (!inside(artifactRoot, filename)) throw new Error(`Unexpected live path: ${name}`);
const stat = fs.lstatSync(filename);
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Invalid live artifact: ${name}`);
if (!name.endsWith(".json")) continue; // External/binary payloads are retained by their owning artifact.
let node;
try { node = JSON.parse(fs.readFileSync(filename,"utf8")); }
catch { throw new Error(`Invalid JSON in live artifact: ${name}`); }
if (!node || typeof node !== "object" || typeof node.hash !== "string" || !node.sourceHash) {
throw new Error(`Invalid live artifact node: ${name}`);
}
if (Object.hasOwn(node,"payload") && node.hash !== hashPayload(node.payload)) {
throw new Error(`Live artifact payload hash mismatch: ${name}`);
}
if (node.payloadBin) {
const binary = path.resolve(projectRoot, node.payloadBin);
if (!fs.existsSync(binary) || sha256(fs.readFileSync(binary)) !== node.hash) {
throw new Error(`Missing or changed binary payload in ${name}`);
}
if (inside(artifactRoot,binary)) {
const ref = posix(path.relative(projectRoot,binary));
if (!visited.has(ref)) { visited.add(ref); queue.push(ref); }
}
}
for (const [key, ref] of Object.entries(node.sourceRef || {})) {
if (typeof ref !== "string") throw new Error(`Invalid parent reference in ${name}`);
const parentFilename = path.resolve(projectRoot, ref);
if (!inside(artifactRoot,parentFilename)) continue;
if (!fs.existsSync(parentFilename)) throw new Error(`Missing parent: ${name} -> ${ref}`);
const parentName = posix(path.relative(projectRoot,parentFilename));
let parentHash;
if (parentFilename.endsWith(".json")) {
let parent;
try { parent = JSON.parse(fs.readFileSync(parentFilename,"utf8")); }
catch { throw new Error(`Bad parent JSON: ${parentName}`); }
parentHash = parent?.hash;
} else parentHash = sha256(fs.readFileSync(parentFilename));
if (!parentHash || !node.sourceHash || node.sourceHash[key] !== parentHash) {
throw new Error(`Recorded parent hash mismatch: ${name} -> ${parentName}`);
}
if (!visited.has(parentName)) { visited.add(parentName); queue.push(parentName); }
}
}
return { targets, visited };
}
async function buildPlan(projectRoot, settingOverlays = [], log = () => {}) {
const artifactRoot = validateArtifactRoot(projectRoot);
const {targets, visited} = await traceCatalog(projectRoot, artifactRoot, settingOverlays, log);
const candidates=[];
const totals={ files:0, bytes:0 };
const retained={ files:0, bytes:0 };
const removal={ files:0, bytes:0 };
const groups = {};
const fullHasher=crypto.createHash("sha256");
const keepHasher=crypto.createHash("sha256");
const removeHasher=crypto.createHash("sha256");
const seen = new Set();
for (const filename of filesUnder(artifactRoot)) {
const name=posix(path.relative(projectRoot,filename));
const stat=fs.lstatSync(filename);
const hash=sha256(fs.readFileSync(filename));
const line=`${name}\0${stat.size}\0${hash}\n`;
const group=name.split("/")[1] || "(root)";
const row=groups[group] ||= {retained:{files:0,bytes:0},removable:{files:0,bytes:0}};
const isLive=visited.has(name);
totals.files++;totals.bytes+=stat.size;
fullHasher.update(line);
const bucket=isLive?retained:removal;
bucket.files++;bucket.bytes+=stat.size;
const section=isLive?row.retained:row.removable;
section.files++;section.bytes+=stat.size;
(isLive?keepHasher:removeHasher).update(line);
if (!isLive) candidates.push({path:name,bytes:stat.size,sha256:hash});
seen.add(name);
}
for (const name of visited) if (!seen.has(name)) throw new Error(`Referenced artifact missing from inventory: ${name}`);
return {schema:SCHEMA,targets,inventory:{...totals,sha256:fullHasher.digest("hex")},
retained:{...retained,sha256:keepHasher.digest("hex")},
proposedRemoval:{...removal,sha256:removeHasher.digest("hex")},
groups,candidates};
}
function cleanEmptyDirectories(directory, isRoot=true) {
for (const entry of fs.readdirSync(directory,{withFileTypes:true})) {
if (entry.isSymbolicLink()) throw new Error(`Symlink appeared during vacuum: ${path.join(directory,entry.name)}`);
if (entry.isDirectory()) cleanEmptyDirectories(path.join(directory,entry.name),false);
}
if (!isRoot && fs.readdirSync(directory).length===0) fs.rmdirSync(directory);
}
async function runVacuum({projectRoot=process.cwd(), settingOverlays=[], apply=false, log=console.log}={}) {
projectRoot=path.resolve(projectRoot);
const artifactRoot=validateArtifactRoot(projectRoot);
const planPath=path.join(projectRoot,"side-effects","optimus-vacuum","plan.json");
const proposed=await buildPlan(projectRoot,settingOverlays,log);
if (!apply) {
fs.mkdirSync(path.dirname(planPath),{recursive:true});
fs.writeFileSync(planPath,JSON.stringify(proposed,null,2)+"\n","utf8");
return {mode:"dry-run",planPath,report:proposed};
}
if (!fs.existsSync(planPath)) throw new Error(`Missing dry-run plan: ${planPath}`);
const prior=JSON.parse(fs.readFileSync(planPath,"utf8"));
if (prior.schema!==SCHEMA || sha256(JSON.stringify(prior))!==sha256(JSON.stringify(proposed))) {
throw new Error("Vacuum plan changed since dry run; nothing removed. Run --vacuum again.");
}
// Full preflight before unlinking the first file. No deletion is attempted
// if any path has changed, disappeared, or been replaced with a symlink.
for (const row of proposed.candidates) {
const file=path.join(projectRoot,row.path);
if (!inside(artifactRoot,file) || !fs.existsSync(file)) throw new Error(`Unsafe or missing candidate: ${row.path}`);
const stat=fs.lstatSync(file);
if (!stat.isFile() || stat.isSymbolicLink() || stat.size!==row.bytes || sha256(fs.readFileSync(file))!==row.sha256) {
throw new Error(`Candidate changed; nothing removed: ${row.path}`);
}
}
for (const row of proposed.candidates) {
const file=path.join(projectRoot,row.path);
const stat=fs.lstatSync(file);
if (!stat.isFile() || stat.isSymbolicLink() || stat.size!==row.bytes || sha256(fs.readFileSync(file))!==row.sha256) {
throw new Error(`Candidate changed during apply; stopped: ${row.path}`);
}
fs.unlinkSync(file);
}
cleanEmptyDirectories(artifactRoot);
return {mode:"applied",planPath,report:proposed};
}
module.exports={runVacuum,buildPlan,traceCatalog};