diff --git a/AGENTS.md b/AGENTS.md index 1055efe..0945005 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -183,3 +183,16 @@ The present direction is therefore to clarify and protect the framework rather t - an opaque content-addressed artifact cache replacing human-readable artifact warehouses; - generalized workflow states, queues, schedulers, or orchestration engines beyond the pull method already in use; - framework-level understanding of LLM providers, translation semantics, publishing semantics, or other domain relationships that belong in modules. + +### Vacuuming the durable artifact warehouse + +`npx optimus --vacuum` examines every declared target through its current pull +chain without allowing rebuilds; `--vacuum --apply` independently rechecks a +previously reviewed checksummed plan before deleting unreachable artifact files. +Do not use a single chosen output as the only root. Every defined target and +every meaningful intermediate artifact it pulls must survive. Keep the +planning report in disposable side-effects. Custom transformers with their own +artifact writers must call `utils.requireCurrentArtifact(filename, isReusable)` +after their freshness check and before any external work, so vacuum fails +closed rather than accidentally regenerating. Do not infer reachability from +`reportEnsure` or `reportBuild`: presentation is diagnostic only. diff --git a/README.md b/README.md index 57327ca..339d8ec 100644 --- a/README.md +++ b/README.md @@ -237,21 +237,29 @@ This behavior is particularly valuable around nondeterministic work. Do not remake an expensive artifact merely to verify it when its actual recipe is unchanged. -A useful LLM-shaped artifact stack can be: +A useful LLM-shaped transformation chain can be: ```text -semantic inputs + formation + model settings - ↓ cheap/deterministic -LLM recipe artifact - ↓ expensive/nondeterministic -LLM response artifact - ↓ cheap/deterministic -parsed / interpreted artifact +semantic parent artifacts + accepted formation/model settings + ↓ assemble transient input and fingerprint +LLM executes only if the semantic result is stale + ↓ +reusable semantic result artifact + ↓ +further meaningful derived artifacts ``` -If only the parser changes, reparse the persisted response. Do not ask the model again. +The assembled request, raw provider response, reasoning and execution trace +belong in disposable side-effects. They need not be stored again as artifacts. +A meaningful interpretation or evidence selection *is* an artifact, even when +its deterministic computation is cheap. An owning transformer may use a +versioned compatibility policy to preserve earlier LLM work across harmless +instruction edits and narrow source changes. -Cheap deterministic work does not require the same protection. If rerunning it is simpler than proving freshness, rerun it. The resulting content hash naturally stops propagation when nothing changed. +Cheap deterministic work may be recalculated more eagerly than expensive work; +when the resulting semantic content hash is unchanged, downstream results can +remain current. Do not persist a temporary prompt or transcript merely to +supply a staleness fingerprint that can be calculated in memory. ## Side effects are not semantic dependencies @@ -263,6 +271,55 @@ A useful test is: > Delete diagnostic side effects, request the same top-level artifact, and do not repeat expensive semantic work unless an actual artifact input changed. +## Catalog-wide artifact vacuum + +Once the complete catalog is current, Optimus can remove stored artifacts that +no longer belong to **any** declared target's active pull tree. This is an +explicit maintenance operation, never part of a normal build: + +```bash +npx optimus # Ensure all defined artifacts first +npx optimus --vacuum # Read-only inventory and proposed removal plan +npx optimus --vacuum --apply # Recheck and apply the identical plan +``` + +The dry run saves `side-effects/optimus-vacuum/plan.json`, listing each candidate +with its byte count and SHA-256 checksum and reporting totals by artifact family. +Nothing is deleted on a dry run. `--apply` recomputes the entire graph and +filesystem inventory, compares the new plan to the saved plan, preflights every +candidate, and removes only unchanged files outside the active graph. The plan +is disposable diagnostic data; remove it freely after maintenance. + +Every entry in `settings/artifacts.json` is an equal root: no named `.all` is +privileged. Even inexpensive intermediate results remain live when a current +transformer pulls them. A result is **not** collectible merely because it is +`sus` or expensive to produce; a result is collectible when no currently +defined target depends upon it. + +The vacuum asks each configured target to establish its own dependencies with +production rebuilding prohibited. Ordinary `utils.resolveArtifact()` work is +verified without invoking its producer. Custom-result transformers that use +`utils.readArtifact()` and their own freshness rules must call +`utils.requireCurrentArtifact(filename, isReusable)` **before** an external +provider call, human request, or other rebuilding work. This is a no-op during +normal execution and fails closed during vacuum inspection. Optimus also +observes artifact file reads during the inspection, verifies stored ancestry +references and payload hashes, and rejects filesystem/network writes or child +process launches during the verification pass. An incomplete, stale or +uninspectable graph aborts the vacuum; run normal Optimus first. + +This verification contract applies to transforms participating in the Optimus +lifecycle. Arbitrary custom code that bypasses the shared lifecycle, opens +files through native extensions, or performs unmanaged external side effects +cannot be proved safe merely by observing the graph; such modules must be +adapted to the inspection contract before vacuuming their projects. Run the +dry-run and keep a backup before using `--apply`. Do not run normal producers +concurrently with a vacuum. + +`--vacuum` accepts the usual `--setting` overlays; it cannot be combined with +`--artifact` or `--relitigate-sus`. Files outside `artifacts/` are not deletion +candidates. No permanent dependency DAG is stored. + ## Named top-level artifacts `settings/artifacts.json` gives humans and automation convenient roots into the pull graph: diff --git a/bin/optimus.js b/bin/optimus.js index 2164ac1..2cc73a7 100644 --- a/bin/optimus.js +++ b/bin/optimus.js @@ -31,6 +31,25 @@ function getSettingOverlays(args) { async function main() { const args = process.argv.slice(2); + if (args.includes("--vacuum")) { + if (args.includes("--artifact") || args.some(arg => arg.startsWith("--artifact=")) || args.includes("--relitigate-sus")) { + throw new Error("--vacuum cannot be combined with --artifact or --relitigate-sus"); + } + const allowed=new Set(["--vacuum","--apply","--setting"]); + for (let i=0;i{ + const file=n=>path.resolve('artifacts',n+'.json'); + async function first(){return utils.resolveArtifact(file('a'),{},async()=>({text:'a'}));} + async function one(){const a=await first();return utils.resolveArtifact(file('first'),{a},async()=>({text:'one'}));} + async function two(){const a=await first();return utils.resolveArtifact(file('second'),{a},async()=>({text:'two'}));} + return {one,two}; +};`); + process.chdir(root); + await initialize(root).buildAll(); + write("artifacts/orphan.json",{obsolete:true}); + write("artifacts/orphan-binary/blob.bin","bytes"); + let result=vacuum(); + assert.equal(result.status,0,result.stderr); + let report=plan(); + assert.equal(report.targets.length,2); + assert.equal(report.retained.files,3); + assert.equal(report.proposedRemoval.files,2); + assert.deepEqual(report.candidates.map(x=>x.path),["artifacts/orphan-binary/blob.bin","artifacts/orphan.json"]); + assert.equal(report.groups["orphan-binary"].removable.files,1); + assert.equal(fs.existsSync(path.join(root,"artifacts/orphan.json")),true); + fs.appendFileSync(path.join(root,"artifacts/orphan.json")," "); + result=vacuum("--apply"); + assert.notEqual(result.status,0,"changed plan must abort"); + assert.match(result.stderr,/plan changed/i); + assert(fs.existsSync(path.join(root,"artifacts/orphan-binary/blob.bin"))); + result=vacuum();assert.equal(result.status,0,result.stderr); + result=vacuum("--apply");assert.equal(result.status,0,result.stderr); + assert(!fs.existsSync(path.join(root,"artifacts/orphan.json"))); + assert(!fs.existsSync(path.join(root,"artifacts/orphan-binary/blob.bin"))); + for(const n of ["a","first","second"])assert(fs.existsSync(path.join(root,`artifacts/${n}.json`))); + result=vacuum();assert.equal(result.status,0,result.stderr); + assert.equal(plan().proposedRemoval.files,0); + // An active JSON descriptor may own a binary result. Preserve both. + const blob=Buffer.from([0,1,2,255]); + const blobFile=path.join(root,"artifacts/binary/payload.bin"); + fs.mkdirSync(path.dirname(blobFile),{recursive:true}); + fs.writeFileSync(blobFile,blob); + const binNode={artifact:"artifacts/binary/node.json",sourceHash:{}, + status:"ok",hash:require("node:crypto").createHash("sha256").update(blob).digest("hex"), + payloadBin:"artifacts/binary/payload.bin"}; + write("artifacts/binary/node.json",binNode); + const modules=JSON.parse(fs.readFileSync(path.join(root,"settings/modules.json"),"utf8")); + modules.binary="./src/binary/index.js"; + write("settings/modules.json",modules); + const catalog=JSON.parse(fs.readFileSync(path.join(root,"settings/artifacts.json"),"utf8")); + catalog.binary={module:"binary",builder:"ensure"}; + write("settings/artifacts.json",catalog); + write("src/binary/index.js",`const path=require("node:path");module.exports=utils=>({ + ensure(){const file=path.resolve('artifacts/binary/node.json'); + const node=utils.readArtifact(file);utils.requireCurrentArtifact(file,Boolean(node));return node;} + });`); + result=vacuum();assert.equal(result.status,0,result.stderr); + assert.equal(plan().retained.files,5); + assert.equal(plan().proposedRemoval.files,0); + // A stale dependency causes a hard abort, never a rebuild. + const file=path.join(root,"artifacts/a.json"); + let node=JSON.parse(fs.readFileSync(file,"utf8")); + node.payload.text="tampered"; + fs.writeFileSync(file,JSON.stringify(node)); + result=vacuum();assert.notEqual(result.status,0); + assert.match(result.stderr,/payload hash mismatch/i); + await initialize(root).buildAll(); // Source hashes still match; runtime does not check its own payload checksum. + fs.rmSync(file); + result=vacuum();assert.notEqual(result.status,0); + assert.match(result.stderr,/missing or stale artifact/i); + await initialize(root).buildAll(); + // The catalog overlay participates in the plan and its full tree. + write("settings/overlays/one.json",{artifacts:{two:{module:"builder",builder:"one"}}}); + result=vacuum("--setting","settings/overlays/one.json"); + assert.equal(result.status,0,result.stderr); + result=vacuum("--apply"); + assert.notEqual(result.status,0); + assert.match(result.stderr,/plan changed/i); + result=vacuum("--setting","settings/overlays/one.json","--apply"); + assert.equal(result.status,0,result.stderr); + // Explicitly protected custom transformers: no generation/model calls. + write("src/builder/index.js",`"use strict"; +const path=require("node:path"); +module.exports=utils=>({async one(){const f=path.resolve('artifacts','first.json');const node=utils.readArtifact(f); + utils.requireCurrentArtifact(f,Boolean(node && node.processing && node.processing.id==='custom')); + throw new Error('EXTERNAL MODEL CALL MUST NEVER HAPPEN');}, + async two(){return utils.resolveArtifact(path.resolve('artifacts/second.json'),{},async()=> 'bad');}});`); + result=vacuum(); assert.notEqual(result.status,0); + assert.match(result.stderr,/missing or stale artifact/i); + assert.doesNotMatch(result.stderr,/EXTERNAL MODEL CALL/i); + // Custom transformers that attempt to write during inspection are blocked. + write("src/builder/index.js",`"use strict"; +const fs=require("node:fs"),path=require("node:path"); +module.exports=utils=>({one(){fs.writeFileSync('DANGEROUS','bad');},two(){return null;}});`); + result=vacuum();assert.notEqual(result.status,0); + assert.match(result.stderr,/forbids writeFileSync/i); + assert(!fs.existsSync(path.join(root,"DANGEROUS"))); + // No catalog must never mean 'delete everything'. + write("settings/artifacts.json",{}); + result=vacuum();assert.notEqual(result.status,0); + assert.match(result.stderr,/empty artifact catalog/i); + console.log("optimus vacuum tests passed"); + }finally{process.chdir(old);fs.rmSync(root,{recursive:true,force:true});} +} +main().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/vacuum.js b/vacuum.js new file mode 100644 index 0000000..3ea504c --- /dev/null +++ b/vacuum.js @@ -0,0 +1,270 @@ +"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 ${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};