more
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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<args.length;i++) {
|
||||
if (args[i]==="--setting") { i++; continue; }
|
||||
if (!allowed.has(args[i]) && !args[i].startsWith("--setting=")) throw new Error(`Unknown vacuum argument: ${args[i]}`);
|
||||
}
|
||||
const { runVacuum } = require("../vacuum");
|
||||
const result = await runVacuum({projectRoot:process.cwd(),settingOverlays:getSettingOverlays(args),apply:args.includes("--apply")});
|
||||
const report = result.report;
|
||||
console.log(JSON.stringify({mode:result.mode,targets:report.targets.length,
|
||||
total:report.inventory,retained:report.retained,removable:report.proposedRemoval,
|
||||
groups:report.groups,plan:result.planPath},null,2));
|
||||
console.log(result.mode==="applied" ? `Removed ${report.proposedRemoval.files} artifact files.` : "No files removed; review the plan, then run --vacuum --apply.");
|
||||
return;
|
||||
}
|
||||
if (args.includes("--apply")) throw new Error("--apply requires --vacuum");
|
||||
const optimus = initialize(process.cwd(), { settingOverlays: getSettingOverlays(args) });
|
||||
const artifactName = getArtifactName(args);
|
||||
const buildOptions = { relitigateSus: args.includes("--relitigate-sus") };
|
||||
|
||||
@@ -93,3 +93,15 @@ The clarified strategy is:
|
||||
- an accepted result that should no longer be evergreen is exported/ejected and becomes ordinary input to another project, intentionally severing the live dependency edge.
|
||||
|
||||
This was a documentation clarification rather than a runtime change.
|
||||
|
||||
## 2026-10-20 — catalog-wide explicit artifact vacuum
|
||||
|
||||
The project-specific storage cleanup prototype was generalized into Optimus:
|
||||
`--vacuum` verifies the present pull graph of **all** configured targets,
|
||||
records an exact per-file checksummed plan in side-effects, and never rebuilds;
|
||||
`--vacuum --apply` repeats the entire inspection and inventories before
|
||||
removing unvisited files. Project-specific freshness still belongs to owning
|
||||
transformers. An inspection-only hook makes custom results fail closed without
|
||||
changing their normal build behavior. Nothing is vacuumed implicitly during
|
||||
`npx optimus` or targeted builds, and the maintenance run does not create a
|
||||
permanent declarative dependency graph.
|
||||
|
||||
@@ -103,3 +103,19 @@ Do not introduce lifecycle restrictions, lazy-loading machinery, or async conven
|
||||
## Blocking flow is intentional
|
||||
|
||||
The project family intentionally targets synchronous, blocking batch execution. Promise-aware behavior that exists today supports legacy callers pending a separate unwind; it is not the desired public programming model. Do not add concurrency or Promise-driven orchestration as an optimization.
|
||||
|
||||
## Catalog-wide cleanup is explicit and pull-derived
|
||||
|
||||
Optimus may reconstruct the live graph from every current named target in
|
||||
`settings/artifacts.json` for maintenance (`--vacuum`). This temporary graph
|
||||
is not a replacement for normal pull execution and is not persisted as a
|
||||
second dependency graph. Any meaningful artifact reached through the current
|
||||
pull graph remains in the warehouse regardless of its regeneration cost.
|
||||
|
||||
Vacuum verification is read-only. If any current target is stale, requires a
|
||||
build, or cannot be inspected, vacuuming aborts. Custom transformers must
|
||||
expose the result of their own freshness check through the Optimus inspection
|
||||
hook before invoking nondeterministic work. Diagnostic reporting is not
|
||||
semantic evidence of reachability. The dry-run plan belongs in disposable
|
||||
side-effects; apply independently recomputes and validates the plan before
|
||||
removal. This is an opt-in maintenance operation, never automatic deletion.
|
||||
|
||||
@@ -197,6 +197,18 @@ function initialize(projectRoot = process.cwd(), options = {}) {
|
||||
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;
|
||||
@@ -214,12 +226,25 @@ function initialize(projectRoot = process.cwd(), options = {}) {
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -263,16 +288,37 @@ function initialize(projectRoot = process.cwd(), options = {}) {
|
||||
buildNode,
|
||||
buildBinaryNode,
|
||||
resolveArtifact: projectResolveArtifact,
|
||||
readArtifact,
|
||||
readArtifact(filename) {
|
||||
const result = readArtifact(filename);
|
||||
if (inspection && result) inspectVisit(filename);
|
||||
return result;
|
||||
},
|
||||
sameSourceHash,
|
||||
statusOf,
|
||||
sus,
|
||||
reconcileArtifactStatus,
|
||||
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,
|
||||
fileNode,
|
||||
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
|
||||
|
||||
+3
-2
@@ -9,10 +9,11 @@
|
||||
"files": [
|
||||
"bin",
|
||||
"index.js",
|
||||
"README.md"
|
||||
"README.md",
|
||||
"vacuum.js"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "node test/smoke.js"
|
||||
"test": "node test/smoke.js && node test/vacuum.js"
|
||||
},
|
||||
"license": "BSD-3-Clause"
|
||||
}
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
"use strict";
|
||||
const assert=require("node:assert/strict");
|
||||
const fs=require("node:fs");
|
||||
const os=require("node:os");
|
||||
const path=require("node:path");
|
||||
const {spawnSync}=require("node:child_process");
|
||||
const {initialize}=require("..");
|
||||
const cli=path.resolve(__dirname,"../bin/optimus.js");
|
||||
const root=fs.mkdtempSync(path.join(os.tmpdir(),"optimus-vacuum-test-"));
|
||||
function write(p,data) {
|
||||
const file=path.join(root,p);
|
||||
fs.mkdirSync(path.dirname(file),{recursive:true});
|
||||
fs.writeFileSync(file,typeof data==="string" ? data : JSON.stringify(data,null,2)+"\n");
|
||||
}
|
||||
function vacuum(...flags){return spawnSync(process.execPath,[cli,"--vacuum",...flags],{cwd:root,encoding:"utf8"});}
|
||||
function plan(){return JSON.parse(fs.readFileSync(path.join(root,"side-effects/optimus-vacuum/plan.json"),"utf8"));}
|
||||
async function main(){
|
||||
const old=process.cwd();
|
||||
try{
|
||||
write("settings/modules.json",{builder:"./src/builder/index.js"});
|
||||
write("settings/artifacts.json",{one:{module:"builder",builder:"one"},two:{module:"builder",builder:"two"}});
|
||||
write("settings/presentation.json",{showOnEnsure:false,showOnBuild:false});
|
||||
write("src/builder/index.js",`"use strict";
|
||||
const fs=require("node:fs"),path=require("node:path");
|
||||
module.exports=utils=>{
|
||||
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;});
|
||||
@@ -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<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};
|
||||
Reference in New Issue
Block a user