Files
optimus/README.md
T
2026-10-26 22:21:04 -05:00

483 lines
21 KiB
Markdown

# optimus
**Optimus is a lightly opinionated framework for organizing pull-driven transformer operations.**
An Optimus project is a team of modules working by a recognizable method. Some modules are transformers that produce durable artifacts. Others may provide services, import data, talk to LLMs or humans, publish results, or coordinate domain-specific work.
A caller asks for the artifact it wants. The responsible module pulls whatever dependencies it needs. Those modules pull their own dependencies. Existing artifacts are reused when their owning transformers consider them current, and work happens only where the chain requires it.
Optimus supplies the shared mechanics. Modules own the meaning of the work.
## The Optimus method
An Optimus project normally has:
```text
settings/
modules.json
artifacts.json
anything-else.json
src/
some-module/
some-transformer/
artifacts/
... durable, inspectable work produced by transformers ...
```
`settings/modules.json` names the participants:
```json
{
"source": "./src/source/index.js",
"translation": "./src/translation/index.js",
"publisher": "./src/publisher/index.js"
}
```
Each module is initialized with the shared Optimus `utils` object:
```js
module.exports = utils => {
const source = utils.loadModule("source");
async function buildSomething(name) {
const input = await source.loadSomething(name);
// Pull more dependencies and do domain work here.
}
return { buildSomething };
};
```
Ordinary recursive module calls are the dependency graph. Optimus does not require a second declarative DAG that duplicates the program.
### Module boundaries and dependency resolution
`settings/modules.json` is the project's composition map. It tells Optimus where a semantically named module comes from. The consumer should know the module name, not its location.
Peer modules therefore load one another through Optimus:
```js
module.exports = utils => {
const segmentation = utils.loadModule("hebrew-segmentation");
// ...
};
```
A module may use ordinary relative imports for private implementation that lives inside that module's own directory:
```js
const parser = require("./parser");
```
A module should not reach sideways into another module by filesystem location:
```js
// Avoid: this couples the consumer to today's repository layout.
const segmentation = require("../hebrew-segmentation");
const helper = require("../shared-lib/agent-transformer");
```
If code in another module directory is a dependency, give it a module identity, register it in `settings/modules.json`, and load it with `utils.loadModule(name)`. If code is truly private implementation, keep it inside the owning module.
This makes Optimus the single dependency resolver for peer modules. A project's composition mapping may change as modules move, split, are extracted, or are provided differently; consumers remain coupled only to the semantic module contract. The current runtime happens to map names to filesystem entry paths, but peer modules should not depend on that representation.
This is dependency injection in the ordinary sense: modules declare what collaborator they need by semantic name, while the project decides what implementation satisfies that name. There should not be a second peer-dependency convention based on relative paths unless a concrete, distinct reason requires one.
## Modules and transformers
A **module** is any participant in the operation.
A **transformer** is a module that can be asked for an artifact and can determine whether the artifact it already has is stale according to that transformer's needs.
All transformers are modules. Not all modules are transformers.
A transformer does not have to map one-to-one with one tiny transformation. One coherent module may own several genuinely related transformations and artifact layers. An importer, for example, may naturally produce volume-, book-, and chapter-level artifacts.
Prefer coherent responsibility over artificial micro-machines.
## Artifacts are an organized warehouse
Artifacts are durable work products, not opaque cache internals.
A human should be able to open a transformer's artifact area and directly find the thing they want to inspect. Persisted metadata exists to explain provenance and help determine freshness, but the artifact itself remains useful, discoverable work.
Artifacts may come from code, LLMs, humans, external systems, or mixtures of them. Optimus does not care who produced the work. The owning transformer cares whether that work remains valid.
Caching is a benefit of durable artifacts, not their purpose.
## Pull, don't push
Optimus is a pull queue.
If a project asks for D:
```text
request D
↓
D asks for B and C
↓ ↓
B asks A C asks A
↓ ↓
existing/current work is reused where possible
```
There is no requirement for a central controller to push A, then B, then C, then D.
This matters especially for expensive or nondeterministic work. A resumed project should not repeat an LLM call merely because some downstream artifact is being rebuilt.
### Ensure dependencies; do not bypass the pull graph
Across module boundaries, the normal operation is to **ensure** the dependency you need. An ensure means: establish the evergreen artifact, reusing the persisted copy when its owning transformer considers it current and rebuilding it when that transformer considers it genuinely stale.
A downstream consumer should not read a persisted upstream artifact directly merely to avoid reevaluating it. Doing so bypasses the pull contract: the consumer gets a historical copy without asking the owning transformer whether that copy is still valid.
If ensuring an expensive artifact causes work that seems unnecessary, ask why its owning transformer considers it stale. Usually the correction belongs in that transformer's freshness rule: depend only on inputs that actually affect the semantic result, preserve accepted expensive work across irrelevant implementation changes, or otherwise make the validity rule match the transformation. A raw read should not be used as a cure for over-sensitive staleness.
Low-level reads remain useful inside transformer-owned lifecycle logic: custom validity checks, migration/adoption, inspection, repair, and similar cases. They are implementation tools for deciding whether owned work is current, not an alternate dependency mechanism.
Sometimes the desired behavior really is **not evergreen**. If a project deliberately accepts a finished result as a stable publication or archival product, export/eject it and use that exported file as input to another project. The receiving project can ensure its own input normally, but there is no live dependency edge back to the old producer and therefore no mechanism by which it can accidentally regenerate the accepted edition.
```text
Evergreen dependency:
consumer -> ensure producer artifact -> reuse or rebuild according to producer freshness
Deliberately frozen handoff:
project A artifact -> output/file -> project B input/file
^ no live edge back to project A
```
These are different semantics and should remain visibly different in the project structure.
## Transformer-owned freshness
Optimus provides common services for recording and comparing dependencies, but the transformer owns the semantic definition of its recipe and freshness.
For the common exact-parent case, `utils.resolveArtifact()` is intentionally small:
```js
const result = await utils.resolveArtifact(
"artifacts/example/result.json",
{
source: sourceNode,
recipe: recipeNode,
},
async () => transformation()
);
```
It:
1. reads the existing artifact if present;
2. compares its complete named `sourceHash` set with the supplied sources;
3. reuses the artifact when the source names and hashes match;
4. otherwise runs the producer;
5. hashes and persists the new result with its ancestry.
That helper expresses one useful freshness policy. It is not a declaration that every transformer in every domain must define staleness exactly this way. A transformer may use `readArtifact()`, `sameSourceHash()`, `fileNode()`, `codeNode()`, or its own domain-specific checks as needed.
The responsibility is simple:
**Before returning persisted work as current, a transformer must verify it according to the inputs and rules that actually matter to that transformation.**
That responsibility is intentionally broader than choosing a hash helper. Each artifact-producing transformer owns the validity, lifecycle, and cleanliness of its own artifacts. It should make freshness decisions with knowledge of the work it performs: cheap versus expensive, deterministic versus flexible/nondeterministic, local computation versus LLM or human work, and any domain-specific signs that an existing payload is unusable.
There is deliberately no universal Optimus staleness formula. A cheap deterministic transformer may reasonably rebuild at the first inconsistency. An expensive LLM transformer may preserve accepted semantic work across many implementation changes while still rejecting a malformed or otherwise nonviable payload and forcing a fresh call. Changes to a transformer's validity policy are semantic behavior changes and should be discussed deliberately rather than smuggled in through a refactor.
Named logic revisions and accepted-revision sets are one useful project-level pattern when behavior evolves. They are available tools, not framework requirements. A shared library may expose a revision identity while each consuming transformer decides which revisions it still accepts. This prevents shared code from becoming an accidental invalidation fan-out.
A transformer also owns cleanup of its artifact area. Durable history may be useful, but a producer should not knowingly accumulate junk artifacts that are no longer valid and are not capable of participating in the active graph.
## Content identity contains propagation
`utils.buildNode(payload, sources)` creates a content-addressed node:
```js
const node = utils.buildNode(payload, {
source: sourceNode,
guidance: guidanceNode,
});
```
A persisted JSON artifact commonly looks like:
```json
{
"artifact": "artifacts/example/result.json",
"sourceHash": {
"source": "<source content hash>",
"guidance": "<guidance content hash>"
},
"sourceRef": {
"source": "artifacts/source/input.json",
"guidance": "src/process/guide.md"
},
"hash": "<payload content hash>",
"payload": "<semantic result>"
}
```
`sourceHash` can establish freshness. `sourceRef` makes ancestry easier for humans to follow. Paths are provenance, not identity.
Children depend on parent content hashes, so a changed parent recipe does not automatically disturb the whole project:
```text
parent recipe changes
→ parent rebuilds
→ rebuilt parent has identical content
→ parent content hash is unchanged
→ children can remain current
```
This behavior is particularly valuable around nondeterministic work.
## Expensive and nondeterministic work
Do not remake an expensive artifact merely to verify it when its actual recipe is unchanged.
A useful LLM-shaped transformation chain can be:
```text
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
```
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 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
Diagnostics, reasoning traces, API transcripts, timing, retries, token counts, and progress information may be useful to retain. They are not automatically semantic inputs.
Projects may keep operational residue in locations such as `side-effects/`, but semantic artifacts should not depend on those files merely because they exist.
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:
```json
{
"ruth.flavor.json": {
"module": "translation",
"builder": "buildFlavor",
"params": ["ruth"]
},
"ruth.en.md": {
"module": "publisher",
"builder": "buildMarkdown",
"params": ["ruth", "en"]
}
}
```
Build one named root:
```bash
npx optimus --artifact ruth.en.md
```
Build every declared root:
```bash
npx optimus
```
A named root does not own all work below it. If multiple products depend on the same investigation artifact, they should pull the same shared artifact rather than duplicating it under whichever root happened to ask first.
## Settings and overlays
`utils.getSettings(name)` reads `settings/<name>.json`.
Optimus deliberately does not understand what arbitrary project settings mean.
Invocation overlays can replace or extend settings for one run:
```bash
npx optimus --artifact psalms.en.md \
--setting settings/overlays/remote.json \
--setting settings/overlays/experiment.json
```
If a setting actually matters to a transformation, that transformer should include it in whatever recipe/freshness representation it uses. Unrelated settings should not become dependencies merely because they exist.
## Framework presentation
Optimus optionally reads `settings/presentation.json`. The framework recognizes two keys and ignores unrelated application-owned presentation settings:
```json
{
"showOnEnsure": false,
"showOnBuild": true
}
```
These are the defaults even when no `presentation.json` exists.
`showOnEnsure` shows the artifact checks Optimus performs while walking the pull graph. This is mainly useful for troubleshooting.
`showOnBuild` announces an artifact immediately after Optimus has decided that work actually needs to run. This is the useful normal view and is enabled by default.
Presentation is deliberately non-semantic. These settings do not participate in artifact identity, freshness, hashes, or processing generations. Applications may keep additional keys in the same settings block; Optimus only reads the keys it owns.
## Artifact utilities
### `utils.buildNode(payload, sources)`
Build a JSON/content node from a semantic payload and optional named parent nodes.
### `utils.buildBinaryNode(filePath, sources)`
Build the binary equivalent using the current file bytes as content identity.
### `utils.resolveArtifact(filename, sources, producer)`
Use the standard exact named-parent-hash freshness policy, run the producer when stale/missing, and persist the result.
### `utils.readArtifact(filename)`
Read a persisted JSON artifact, or return `null` when no usable artifact exists. This is a low-level lifecycle utility, not an alternative to ensuring a dependency owned by another transformer.
### `utils.sameSourceHash(node, sources)`
Compare a persisted node with an exact current named parent-hash set.
### `utils.invalidateArtifact(filename)`
Delete one artifact or artifact subtree. Descendants elsewhere are not proactively deleted; the next pull request discovers what actually needs rebuilding.
### `utils.fileNode(filename)`
Create a content node from authoritative file bytes.
### `utils.codeNode(label, value)`
Create a content node from a function or other code-like value when implementation itself is a meaningful recipe input.
### `utils.reportEnsure(label)` and `utils.reportBuild(label)`
Most transformers do not need these because `utils.resolveArtifact()` reports its own ensure/build decisions. A transformer with custom freshness semantics may use them so Optimus still owns console policy:
```js
utils.reportEnsure("dexter/summary");
if (needsWork) utils.reportBuild("dexter/summary");
```
The transformer reports the event; Optimus decides whether the configured presentation policy makes it visible.
### `utils.setArtifactOutcome(message)`
This older top-level outcome hook remains available for compatibility and troubleshooting output when `showOnEnsure` is enabled. It is presentation state only and does not participate in freshness or identity.
## Human participation is allowed
Optimus does not require artifacts to be machine-generated.
A future transformer may interview a human, present an edit list for acceptance/rejection, collect manually authored guide entries, or allow a human to explicitly stamp prepared data as valid. That interaction belongs to the transformer or another module that owns the experience.
Optimus does not need a generic human-task system to support human-produced artifacts.
## What Optimus intentionally does not own
Optimus does not define:
- LLM providers or model configuration;
- translation semantics;
- publishing semantics;
- generic approval workflows;
- a universal transformer interface;
- one-module-per-transformation architecture;
- a central declarative DAG;
- domain-specific artifact validity.
It provides services, not restrictions.
## Regression check
Optimus ships with a small smoke test:
```bash
npm test
```
The test covers module/settings behavior, artifact hashing and persistence, content-based propagation containment, targeted invalidation, overlays, binary nodes, and framework presentation defaults/reporting.
Project-level tests should additionally protect whatever freshness semantics their own transformers consider important.
## More design context
See:
- `AGENTS.md` — development philosophy and framework boundaries;
- `docs/intentional-behavior.md` — behavior that should not be casually changed during refactors;
- `docs/history.md` — why the current shape exists;
- `docs/ideas.md` — possibilities deliberately left unbuilt until evidence requires them.