Compare commits
2
Commits
5069f75171
...
9b848cefcf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9b848cefcf | ||
|
|
a7ea0b20a0 |
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
bin/
|
||||
*.zip
|
||||
@@ -0,0 +1,185 @@
|
||||
# Development Philosophy
|
||||
|
||||
## Simplicity is the default
|
||||
|
||||
Speculative architecture always has negative value.
|
||||
|
||||
The cost of writing code is small compared with the cost of carrying it. Every abstraction, hook, compatibility layer, option, fallback, extension point, and anticipated future feature becomes something the project must understand and preserve. Worse, later work begins building on guesses about a future that has not arrived yet.
|
||||
|
||||
If we understand A and B, partly understand C and D, and only imagine E, build A and B. Do not pour foundations for C, D, or E. When C becomes real, A and B will have taught us things we could not know beforehand. That evidence lets us build C once and integrate it with what actually exists. Premature preparation for E can occupy the very ground the real E eventually needs and can force A through D to depend on a mistaken future.
|
||||
|
||||
The only reliable speculation is that simplicity will pay off.
|
||||
|
||||
Build the smallest thing that fully serves the need we concretely understand. Do not future-proof by predicting the future. Preserve the future by refusing to obstruct it.
|
||||
|
||||
## Discussion before action
|
||||
|
||||
A problem report is information, not an instruction to patch the nearest code.
|
||||
|
||||
When something breaks, first understand what happened, why it happened, which behavior was intentional, and what solution landscape the evidence supports. A clear path is not necessarily the right path. The right path tends to reveal itself when investigation and discussion converge on an obvious next step.
|
||||
|
||||
This is not ceremony. The discussion may be brief. The rule is simply that action follows understanding rather than replacing it.
|
||||
|
||||
Do not make meaningful behavioral or architectural changes merely because they appear straightforward. Surface the evidence, alternatives, and consequences first and agree on direction.
|
||||
|
||||
## Beauty over perfection
|
||||
|
||||
We are not building machinery to eliminate every imperfect judgment, irregular case, or possible mistake. Predictably good, useful, approachable work is more valuable than elaborate systems designed to force perfection.
|
||||
|
||||
An occasional exception is allowed to remain an exception. Do not immediately turn anomalies into rules, validation systems, abstractions, fallbacks, or special cases. Forgive exceptions until repeated evidence shows that the exception is actually part of the shape of the problem.
|
||||
|
||||
This applies to code and to the content these tools help produce. Complexity introduced to prevent every possible imperfection often damages the work more than the imperfection would have.
|
||||
|
||||
## Follow evidence without an agenda
|
||||
|
||||
Investigate the actual code, data, failures, and outputs rather than speculating about what they probably mean. Do not steer evidence toward a preferred architecture or conclusion.
|
||||
|
||||
For translation and ancient-text work, the received text is the authority. Tradition is context, not a destination. We are not trying to reinforce tradition or tear it down, and we do not bend the text toward doctrine, dogma, skepticism, apologetics, or novelty. The aim is unbiased, approachable, useful, compelling translation of ancient wisdom.
|
||||
|
||||
Not every participant in a creative or translation pipeline produces evidence. Explorers, philosophers, and literary voices may speculate, reach, or occasionally indulge wishful thinking when that is useful to their role. Be rigorous about what is called evidence and which roles have authority to alter the received text; do not turn the entire endeavor into an academic apparatus in pursuit of impossible perfection.
|
||||
|
||||
## Synchronous blocking execution is the intended project-family architecture
|
||||
|
||||
The applications using Optimus are blocking batch tools, not concurrent servers. Their desired control flow is one path at a time: ensure one dependency, finish it, persist/publish it, return, then continue. Do not treat Node's conventional async style as a design requirement.
|
||||
|
||||
Optimus currently contains Promise-aware plumbing because the existing projects still contain legacy async functions. That is transitional compatibility, not an invitation to spread async/await, Promise returns, callback orchestration, parallel sibling ensures, or queues. A separate refactor will unwind this plumbing. Until then, do not make that future conversion harder.
|
||||
|
||||
# Optimus
|
||||
|
||||
Optimus is a lightly opinionated framework for organizing pull-driven transformer operations.
|
||||
|
||||
Like Optimus Prime, Optimus does not solve every problem itself. It leads a team that works by a recognizable method. An Optimus project should clearly look and behave like an Optimus project even though its modules remain loosely coupled and domain-specific.
|
||||
|
||||
Optimus organizes modules. Some modules are transformers. Some are not. Optimus also participates directly by providing the shared services that let modules locate one another, request work, wrap results in metadata, persist artifacts, and determine whether previously completed work can still be trusted.
|
||||
|
||||
## Core concepts
|
||||
|
||||
### Modules are the team
|
||||
|
||||
A module is a participant in an Optimus operation. It may transform data, provide services, coordinate work, interact with an LLM, interact with a human, import external material, publish results, or do something else entirely.
|
||||
|
||||
Optimus gives modules a shared project environment and a way to locate one another without requiring a central monolith.
|
||||
|
||||
### Peer dependencies are resolved by Optimus
|
||||
|
||||
Treat each registered module as a dependency-injection boundary. A module may use relative imports for private implementation files inside its own module directory. It should not know the filesystem location of a peer module.
|
||||
|
||||
When one module depends on another, resolve that dependency by semantic name through `utils.loadModule(name)`. `settings/modules.json` is the composition map that decides which implementation/location satisfies that name.
|
||||
|
||||
```js
|
||||
module.exports = utils => {
|
||||
const source = utils.loadModule("standard-source");
|
||||
return { /* ... */ };
|
||||
};
|
||||
```
|
||||
|
||||
Do not bypass Optimus with sideways imports such as `require("../standard-source")` or `require("../lib/...")` when that neighboring directory is functioning as a peer module. If shared code deserves an independent neighboring module directory, register it and load it through Optimus. If it is private to one module, keep it inside that module.
|
||||
|
||||
The reason is architectural rather than stylistic. Consumers should depend on a peer's semantic contract, not today's repository layout. That allows the project mapping to relocate, extract, package, or replace modules later without rewriting their consumers, and it prevents two competing dependency-resolution systems from emerging without two distinct needs.
|
||||
|
||||
### Transformers are artifact-producing modules
|
||||
|
||||
A transformer is a module that can be asked for an artifact and can determine whether an existing artifact is stale according to that transformer's needs.
|
||||
|
||||
All transformers are modules. Not all modules are transformers.
|
||||
|
||||
A transformer is not required to be a tiny one-transformation machine. One coherent transformer module may own several closely related transformations and several artifact layers. For example, an importer may naturally produce volume-, book-, and chapter-level artifacts. Prefer coherent responsibility over artificial micro-modules.
|
||||
|
||||
### Artifacts are durable work, not a private cache
|
||||
|
||||
A transformer's artifact area is an organized workbench and warehouse. Humans should be able to enter it and directly find the artifact they want to inspect. Do not turn artifact storage into an opaque hash cache or private implementation laboratory.
|
||||
|
||||
Artifacts may be produced by deterministic code, LLMs, humans, external systems, or combinations of them. Optimus does not privilege one producer type over another.
|
||||
|
||||
Caching is a useful behavior of durable artifacts, not their identity. Persist work because the work is meaningful, inspectable, reusable, expensive, nondeterministic, or useful for evaluating freshness—not because every function deserves a cache entry.
|
||||
|
||||
### Pull drives the operation
|
||||
|
||||
Optimus is a pull queue, not a push pipeline runner.
|
||||
|
||||
A caller asks for a desired artifact. The responsible module asks for what it needs. Those modules ask for what they need. Existing work is reused where it remains valid, and work happens only where the dependency chain requires it.
|
||||
|
||||
Do not replace this with a centrally scheduled sequence or a duplicate declarative DAG unless concrete evidence proves the ordinary module calls are insufficient.
|
||||
|
||||
## Transformer-owned validity
|
||||
|
||||
Optimus provides services that make freshness easy to record and evaluate. Optimus does not own the semantic definition of freshness for every transformation.
|
||||
|
||||
The transformer owns its recipe: which inputs matter, which implementation or settings changes matter, and what must be compared before an artifact can be reused. `resolveArtifact()` and `sameSourceHash()` provide a small, useful exact-parent-hash policy, but they are framework services, not a restriction that every transformer must define validity in exactly the same way.
|
||||
|
||||
Every transformer is responsible for verifying that the artifacts it returns are current according to its own declared needs.
|
||||
|
||||
That ownership includes artifact lifecycle and cleanup, not only dependency hashes. A transformer should understand whether its work is cheap or expensive, deterministic or flexible/nondeterministic, and whether payload-level defects can make an otherwise well-provenanced artifact unusable. Cheap deterministic work may choose eager recalculation. Expensive LLM work will often be more conservative, while still needing a deliberate way to force a fresh call when the actual result is not viable.
|
||||
|
||||
There is no universal Optimus staleness policy and there should not become one. Named logic revisions and accepted-revision sets are an available pattern when a transformer needs compatibility tracking, not a requirement that every transformer version itself. Likewise, a shared utility or wisdom stack may expose a revision identity without making every consumer stale; the consuming transformer decides whether that revision participates in its own validity rule.
|
||||
|
||||
Changes to those validity judgments are behavioral decisions. Discuss them deliberately rather than allowing a cleanup/refactor to redefine artifact freshness accidentally.
|
||||
|
||||
A transformer also owns keeping its artifact warehouse meaningful. Preserve useful durable history, but do not knowingly retain junk artifacts that are no longer valid and cannot participate in the active graph.
|
||||
|
||||
Do not centralize domain-specific invalidation policy into Optimus merely because several transformers use the same helper today.
|
||||
|
||||
## Services, not restrictions
|
||||
|
||||
Optimus is a framework, but it should preserve maximum flexibility within its operating method.
|
||||
|
||||
Optimus should make it easy to:
|
||||
|
||||
- organize modules;
|
||||
- locate modules by semantic name;
|
||||
- read project settings;
|
||||
- request named top-level artifacts;
|
||||
- pull dependencies recursively through ordinary code;
|
||||
- wrap work in content/provenance metadata;
|
||||
- persist and read durable artifacts;
|
||||
- evaluate common freshness patterns;
|
||||
- invalidate targeted persisted work;
|
||||
- report artifact ensure/build decisions according to project presentation settings.
|
||||
|
||||
Optimus should not decide:
|
||||
|
||||
- what a domain artifact means;
|
||||
- what a transformer's complete recipe is;
|
||||
- how a human participates in a transformation;
|
||||
- how an LLM is configured or called;
|
||||
- how a translation is judged;
|
||||
- whether a module must be a transformer;
|
||||
- how many related transformations one module may own;
|
||||
- what every artifact directory must contain beyond what the owning transformer needs.
|
||||
|
||||
If a human-interaction workflow becomes useful, a module such as a future Bumblebee transformer can own that experience and persist/stamp its results. Optimus does not need a generic human-task system in order to permit human-produced artifacts.
|
||||
|
||||
## Intentional boundaries
|
||||
|
||||
The following behavior is deliberate. Do not remove or substantially reshape it without discussion:
|
||||
|
||||
- Optimus is pull-driven rather than a centrally pushed stage runner.
|
||||
- Modules are the primary participants; transformers are a subset of modules.
|
||||
- Peer-module dependencies are resolved by semantic name through Optimus; modules do not reach across peer boundaries by filesystem path.
|
||||
- Ordinary module calls may express the dependency graph. A second graph definition is not required.
|
||||
- Transformer modules may own multiple closely related transformations.
|
||||
- Transformers own their freshness semantics; Optimus supplies common mechanisms.
|
||||
- Durable artifacts are human-inspectable work products, not opaque cache internals.
|
||||
- Content hashes stop unnecessary downstream propagation when rebuilt content is unchanged.
|
||||
- Human-, LLM-, code-, and externally-produced work may all become legitimate artifacts when the owning transformer knows how to validate them.
|
||||
- Side effects and diagnostics do not become semantic dependencies merely because they are useful to retain.
|
||||
- Presentation (`showOnEnsure`, `showOnBuild`, `reportEnsure()`, `reportBuild()`, and legacy `setArtifactOutcome()`) is reporting only and never participates in artifact identity or freshness.
|
||||
- Settings remain domain-agnostic JSON owned by the Optimus project. Optimus does not need to understand their meaning.
|
||||
- Module initialization is free to do the work its module actually needs. Do not add lifecycle restrictions merely to force every module into the same shape.
|
||||
|
||||
## Current direction
|
||||
|
||||
The current Optimus runtime already expresses this vision with a small amount of machinery: settings, modules, named artifacts, recursive module calls, artifact nodes, persistence helpers, hashing, invalidation, and CLI orchestration.
|
||||
|
||||
The present direction is therefore to clarify and protect the framework rather than expand it. Add capability only when an actual Optimus project demonstrates that the current services are insufficient.
|
||||
|
||||
## Deliberately not doing yet
|
||||
|
||||
- generic human-task or approval workflow infrastructure;
|
||||
- a universal transformer interface beyond the behavior actual modules already need;
|
||||
- one-module-per-transformation enforcement;
|
||||
- a central declarative dependency graph;
|
||||
- schemas or type systems for arbitrary project settings;
|
||||
- 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.
|
||||
@@ -1,181 +1,425 @@
|
||||
# optimus
|
||||
|
||||
A deliberately small project runtime for initialized modules, settings, named artifacts, and transformer-node helpers.
|
||||
**Optimus is a lightly opinionated framework for organizing pull-driven transformer operations.**
|
||||
|
||||
## Project shape
|
||||
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 host project provides JSON settings in `./settings/`:
|
||||
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 ...
|
||||
```
|
||||
|
||||
`modules.json` maps semantic module names to initializer modules:
|
||||
`settings/modules.json` names the participants:
|
||||
|
||||
```json
|
||||
{
|
||||
"chatter": "./tree/chatter/index.js",
|
||||
"markdown-builder": "./tree/markdown-builder/index.js"
|
||||
"source": "./src/source/index.js",
|
||||
"translation": "./src/translation/index.js",
|
||||
"publisher": "./src/publisher/index.js"
|
||||
}
|
||||
```
|
||||
|
||||
Each module exports an initializer that receives the same shared `utils` object:
|
||||
Each module is initialized with the shared Optimus `utils` object:
|
||||
|
||||
```js
|
||||
module.exports = utils => {
|
||||
function doSomething() {
|
||||
const chatter = utils.loadModule("chatter");
|
||||
const llm = utils.getSettings("llm");
|
||||
const source = utils.loadModule("source");
|
||||
|
||||
async function buildSomething(name) {
|
||||
const input = await source.loadSomething(name);
|
||||
// Pull more dependencies and do domain work here.
|
||||
}
|
||||
|
||||
return { doSomething };
|
||||
return { buildSomething };
|
||||
};
|
||||
```
|
||||
|
||||
## Utilities
|
||||
Ordinary recursive module calls are the dependency graph. Optimus does not require a second declarative DAG that duplicates the program.
|
||||
|
||||
### `utils.loadModule(name)`
|
||||
### Module boundaries and dependency resolution
|
||||
|
||||
Returns the initialized module registered under that semantic name.
|
||||
`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.
|
||||
|
||||
### `utils.getSettings(name)`
|
||||
Peer modules therefore load one another through Optimus:
|
||||
|
||||
Returns the parsed contents of `./settings/<name>.json`.
|
||||
```js
|
||||
module.exports = utils => {
|
||||
const segmentation = utils.loadModule("hebrew-segmentation");
|
||||
// ...
|
||||
};
|
||||
```
|
||||
|
||||
### `utils.hashPayload(value)`
|
||||
A module may use ordinary relative imports for private implementation that lives inside that module's own directory:
|
||||
|
||||
Returns a SHA-256 hex hash of `JSON.stringify(value)`. No key sorting or normalization is performed.
|
||||
```js
|
||||
const parser = require("./parser");
|
||||
```
|
||||
|
||||
### `utils.buildNode(payload, sources = {})`
|
||||
A module should not reach sideways into another module by filesystem location:
|
||||
|
||||
Builds a transformer-node packet from a payload and already-loaded source nodes:
|
||||
```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, {
|
||||
hebrew: hebrewNode,
|
||||
source: sourceNode,
|
||||
guidance: guidanceNode,
|
||||
});
|
||||
```
|
||||
|
||||
Result:
|
||||
A persisted JSON artifact commonly looks like:
|
||||
|
||||
```json
|
||||
{
|
||||
"artifact": "artifacts/example/result.json",
|
||||
"sourceHash": {
|
||||
"hebrew": "<hebrewNode.hash>",
|
||||
"guidance": "<guidanceNode.hash>"
|
||||
"source": "<source content hash>",
|
||||
"guidance": "<guidance content hash>"
|
||||
},
|
||||
"hash": "<hash of payload>",
|
||||
"payload": "<payload>"
|
||||
"sourceRef": {
|
||||
"source": "artifacts/source/input.json",
|
||||
"guidance": "src/process/guide.md"
|
||||
},
|
||||
"hash": "<payload content hash>",
|
||||
"payload": "<semantic result>"
|
||||
}
|
||||
```
|
||||
|
||||
Optimus does not persist or validate the node. The owning module decides where its artifacts live and when to rebuild them.
|
||||
`sourceHash` can establish freshness. `sourceRef` makes ancestry easier for humans to follow. Paths are provenance, not identity.
|
||||
|
||||
### `utils.buildBinaryNode(filePath, sources = {})`
|
||||
Children depend on parent content hashes, so a changed parent recipe does not automatically disturb the whole project:
|
||||
|
||||
Builds the binary equivalent of a transformer-node packet. The supplied path is kept as the usable binary payload locator, while `hash` is computed from the file bytes:
|
||||
|
||||
```js
|
||||
const node = utils.buildBinaryNode(resolvedCoverPath);
|
||||
```text
|
||||
parent recipe changes
|
||||
→ parent rebuilds
|
||||
→ rebuilt parent has identical content
|
||||
→ parent content hash is unchanged
|
||||
→ children can remain current
|
||||
```
|
||||
|
||||
Result:
|
||||
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 artifact stack can be:
|
||||
|
||||
```text
|
||||
semantic inputs + formation + model settings
|
||||
↓ cheap/deterministic
|
||||
LLM recipe artifact
|
||||
↓ expensive/nondeterministic
|
||||
LLM response artifact
|
||||
↓ cheap/deterministic
|
||||
parsed / interpreted artifact
|
||||
```
|
||||
|
||||
If only the parser changes, reparse the persisted response. Do not ask the model again.
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
## Named top-level artifacts
|
||||
|
||||
`settings/artifacts.json` gives humans and automation convenient roots into the pull graph:
|
||||
|
||||
```json
|
||||
{
|
||||
"sourceHash": {},
|
||||
"hash": "<SHA-256 of file bytes>",
|
||||
"payloadBin": "<filePath>"
|
||||
}
|
||||
```
|
||||
|
||||
Derived binary artifacts can name source nodes in the same way as `buildNode()`:
|
||||
|
||||
```js
|
||||
return utils.buildBinaryNode(pdfPath, {
|
||||
volume: volumeNode,
|
||||
style: styleNode,
|
||||
});
|
||||
```
|
||||
|
||||
`buildBinaryNode()` does not copy the file, interpret the path, or know what kind of binary it represents. It hashes the bytes currently at `filePath` and returns that path unchanged as `payloadBin`.
|
||||
|
||||
## Artifacts
|
||||
|
||||
`settings/artifacts.json` explicitly names the module and public builder function for each top-level artifact:
|
||||
|
||||
```json
|
||||
{
|
||||
"job.en.md": {
|
||||
"module": "unpointed-hebrew-markdown-builder",
|
||||
"builder": "buildMarkdownOutput",
|
||||
"params": ["job", "en"]
|
||||
"ruth.flavor.json": {
|
||||
"module": "translation",
|
||||
"builder": "buildFlavor",
|
||||
"params": ["ruth"]
|
||||
},
|
||||
"ruth.en.md": {
|
||||
"module": "publisher",
|
||||
"builder": "buildMarkdown",
|
||||
"params": ["ruth", "en"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Build one artifact:
|
||||
Build one named root:
|
||||
|
||||
```bash
|
||||
npx optimus --artifact job.en.md
|
||||
npx optimus --artifact ruth.en.md
|
||||
```
|
||||
|
||||
Build every declared artifact:
|
||||
Build every declared root:
|
||||
|
||||
```bash
|
||||
npx optimus
|
||||
```
|
||||
|
||||
Artifacts are logical requested outcomes. Their modules own filenames, directories, persistence, cache policy, and dependency behavior.
|
||||
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.
|
||||
|
||||
A builder may call `utils.setArtifactOutcome("up to date")` (or another concise outcome) before returning. Optimus prints the requested artifact ID before invoking the builder and prints that outcome afterward; builders that do not report one receive the generic `completed — success` result.
|
||||
## Settings and overlays
|
||||
|
||||
## Invocation setting overlays
|
||||
`utils.getSettings(name)` reads `settings/<name>.json`.
|
||||
|
||||
Optimus loads the project defaults from direct `settings/*.json` files. Each filename remains a free-form settings name available through `utils.getSettings(name)`.
|
||||
Optimus deliberately does not understand what arbitrary project settings mean.
|
||||
|
||||
A process can layer one or more JSON overlays on top of those defaults:
|
||||
|
||||
```bash
|
||||
npx optimus --artifact psalms.en.md --setting settings/overlays/remote.json
|
||||
```
|
||||
|
||||
Multiple overlays are applied left-to-right:
|
||||
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/experimental-model.json
|
||||
--setting settings/overlays/experiment.json
|
||||
```
|
||||
|
||||
An overlay is one object whose top-level keys are ordinary settings names:
|
||||
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
|
||||
{
|
||||
"llm": {
|
||||
"host": "remote-box",
|
||||
"model": "remote-model"
|
||||
}
|
||||
"showOnEnsure": false,
|
||||
"showOnBuild": true
|
||||
}
|
||||
```
|
||||
|
||||
Overlay behavior is deliberately small:
|
||||
These are the defaults even when no `presentation.json` exists.
|
||||
|
||||
- object over object: recursively overlay properties;
|
||||
- arrays: replace the previous array;
|
||||
- scalars: replace the previous value;
|
||||
- `null`: replace the previous value with `null`;
|
||||
- omitted properties: inherit the value underneath;
|
||||
- an overlay may introduce a new free-form settings name.
|
||||
`showOnEnsure` shows the artifact checks Optimus performs while walking the pull graph. This is mainly useful for troubleshooting.
|
||||
|
||||
`utils.getSettings("llm")` sees only the resulting effective settings. Modules do not know which values came from defaults versus invocation overlays.
|
||||
`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.
|
||||
|
||||
Overlay paths are resolved relative to the project root unless absolute.
|
||||
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.
|
||||
|
||||
## Build-all memory behavior
|
||||
## Artifact utilities
|
||||
|
||||
`buildAll()` awaits each declared artifact sequentially and does not retain prior artifact results. Artifact builders may still return either ordinary values or Promises; the runtime remains compatible with genuinely asynchronous work such as LLM requests.
|
||||
### `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.
|
||||
|
||||
+3
-2
@@ -33,16 +33,17 @@ async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
const optimus = initialize(process.cwd(), { settingOverlays: getSettingOverlays(args) });
|
||||
const artifactName = getArtifactName(args);
|
||||
const buildOptions = { relitigateSus: args.includes("--relitigate-sus") };
|
||||
|
||||
if (artifactName) {
|
||||
await optimus.buildArtifact(artifactName);
|
||||
await optimus.buildArtifact(artifactName, buildOptions);
|
||||
console.log(`Artifact complete: ${artifactName}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const artifacts = optimus.getSettings("artifacts");
|
||||
const names = Object.keys(artifacts);
|
||||
await optimus.buildAll();
|
||||
await optimus.buildAll(buildOptions);
|
||||
console.log(names.length ? `Artifacts complete: ${names.join(", ")}` : "No artifacts configured.");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
# Design History
|
||||
|
||||
This is a reasoning history, not a commit log. It records the problems that shaped Optimus so later changes can distinguish intentional design from accidental implementation.
|
||||
|
||||
## Durable work instead of rerunning pipelines
|
||||
|
||||
Optimus grew around a practical problem: expensive and nondeterministic work should survive restarts and downstream changes.
|
||||
|
||||
A conventional pipeline runner tends to think in execution order. Optimus instead asks for a desired artifact and walks downward through the work needed to establish it. This made persisted intermediate results first-class rather than incidental cache files.
|
||||
|
||||
The important consequence was a pull-driven operation: request what you want, recursively establish what it depends on, and wake only the work that is actually missing or stale.
|
||||
|
||||
## Content identity stopped unnecessary invalidation
|
||||
|
||||
A parent transformation can become stale because its recipe changed and still reproduce exactly the same semantic output.
|
||||
|
||||
If every downstream artifact invalidated merely because the parent reran, expensive/nondeterministic work would be repeated unnecessarily. Optimus therefore uses content hashes as the identity passed downstream. A rebuilt parent with unchanged content does not force descendants to rebuild.
|
||||
|
||||
This was especially valuable for LLM-heavy pipelines where unnecessary reruns can produce different answers even when nothing semantically changed.
|
||||
|
||||
## Complete named parent sets became a useful default recipe check
|
||||
|
||||
`resolveArtifact()` compares the complete named set of source hashes rather than only overlapping hashes. Adding, removing, or renaming a semantic parent is therefore a recipe change under that helper.
|
||||
|
||||
The names matter because they describe roles, not just byte values.
|
||||
|
||||
This exact-source-set policy remains a useful framework service, but later clarification made an important boundary explicit: transformers own their own semantic freshness rules. `resolveArtifact()` is a strong default mechanism, not a universal definition imposed by Optimus.
|
||||
|
||||
## Artifacts remained readable instead of becoming an opaque cache
|
||||
|
||||
As more intermediate work became durable, it became useful to inspect it directly while debugging, evaluating LLM output, comparing translations, and understanding provenance.
|
||||
|
||||
Artifact directories therefore function as organized workbenches/warehouses. They are not intended to become private implementation storage addressed only by hashes.
|
||||
|
||||
`sourceRef` supports human navigation while `sourceHash` remains the content-validity mechanism.
|
||||
|
||||
## Modules became the team; transformers remained a subset
|
||||
|
||||
Optimus projects naturally accumulated participants that did not fit a strict "one transformer = one stage" model: source loaders, publishers, LLM wrappers, coordination helpers, and other services.
|
||||
|
||||
The resulting model is deliberately loose:
|
||||
|
||||
- Optimus organizes modules.
|
||||
- Some modules are transformers.
|
||||
- A transformer may own several closely related transformations.
|
||||
- Ordinary module calls may express dependency relationships.
|
||||
|
||||
This avoids both a central monolith and artificial micro-transformers.
|
||||
|
||||
## Humans are legitimate artifact producers
|
||||
|
||||
The first Optimus projects mostly received human-authored material through input folders and then transformed it mechanically or through LLMs.
|
||||
|
||||
The framework was later clarified to permit humans as active participants inside transformations as well. A module may interview a human, collect approvals, accept manually authored guide entries, or allow a human to stamp prepared material as valid.
|
||||
|
||||
No Optimus-level human workflow system was added. If recurring human interaction needs reusable machinery, it can emerge as its own module (for example a future Bumblebee transformer) once real implementations provide evidence for what that machinery should be.
|
||||
|
||||
## 2026-09-09 — framework vision documented without runtime change
|
||||
|
||||
The project documentation was revised to describe Optimus as a lightly opinionated pull-driven transformer framework rather than primarily as a durable artifact resolver.
|
||||
|
||||
This was a clarification of the implementation's existing shape, not a runtime redesign.
|
||||
|
||||
The discussion established these intentional boundaries:
|
||||
|
||||
- Optimus organizes modules and participates through shared framework services.
|
||||
- Transformers are artifact-producing/validating modules, not mandatory micro-machines.
|
||||
- Freshness semantics ultimately belong to each transformer.
|
||||
- Artifact areas are readable workbenches/warehouses.
|
||||
- Human, LLM, external, and deterministic producers are all permitted.
|
||||
- Optimus provides services rather than domain restrictions.
|
||||
- No generic human-task system, central DAG, universal transformer interface, or other speculative framework machinery should be added without evidence.
|
||||
|
||||
## 2026-09-10 — useful build reporting without the full role call
|
||||
|
||||
Real translation runs showed that printing every already-current artifact check made normal console output noisy. The useful operational fact was usually the moment Optimus decided that work actually had to run.
|
||||
|
||||
Optimus therefore gained two optional presentation settings: `showOnEnsure` (default false) and `showOnBuild` (default true). Standard `resolveArtifact()` work reports automatically, while custom-validity transformers can report the same events through tiny framework hooks. Presentation remains completely outside artifact semantics.
|
||||
|
||||
This also reinforced an earlier framework principle: Optimus conveniences are services, not contracts. A transformer with unusual validity rules does not have to adopt `resolveArtifact()` merely to obtain consistent console behavior.
|
||||
|
||||
|
||||
|
||||
## 2026-10-06 — ensure remains the dependency contract
|
||||
|
||||
Publication work exposed an important distinction between expensive evergreen artifacts and intentionally frozen editions. The tempting shortcut was to read an existing expensive artifact directly so a downstream publisher could not accidentally wake it. That would have inverted Optimus's pull model: the downstream consumer, rather than the owning transformer, would decide whether a historical copy was acceptable.
|
||||
|
||||
The clarified strategy is:
|
||||
|
||||
- live dependencies are ensured normally;
|
||||
- if an ensure wakes work unnecessarily, the owning transformer's freshness inputs or validity policy are too broad and should be corrected there;
|
||||
- low-level artifact reads remain available for transformer-owned validity, migration, repair, and inspection;
|
||||
- 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.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Ideas and Deferred Possibilities
|
||||
|
||||
This file is intentionally not a roadmap. Items here are possibilities or observations that do not yet have enough evidence to justify framework complexity.
|
||||
|
||||
The default action for every item is: leave it alone until real Optimus projects demonstrate the need.
|
||||
|
||||
## Human-interaction modules
|
||||
|
||||
A future module (informally imagined as something like Bumblebee) could own reusable human interaction: interviews, approval queues, manual guide entry, or explicit stamping of human-authored artifacts.
|
||||
|
||||
Optimus itself does not need a human-task subsystem. Build a concrete module first if/when a real workflow requires one. Only repeated implementations should motivate shared machinery.
|
||||
|
||||
## More transformer helpers
|
||||
|
||||
Different domains may eventually repeat freshness or persistence patterns that are not covered cleanly by `resolveArtifact()` and the current node helpers.
|
||||
|
||||
Do not add generic recipe objects, transformer base classes, validation interfaces, or capability registries in anticipation of that possibility. Let several real transformers reveal the common shape first.
|
||||
|
||||
## Artifact browsing tools
|
||||
|
||||
Because artifact areas are intended to be human-readable warehouses, a project may someday benefit from optional browsing/search tooling.
|
||||
|
||||
Do not restructure artifact storage around such a tool. The files should remain directly understandable without it.
|
||||
|
||||
## Module initialization
|
||||
|
||||
Modules currently initialize at project startup while transformation work remains pull-driven.
|
||||
|
||||
If a future project demonstrates that initialization itself is expensive or has harmful side effects, reconsider lazy initialization then. Do not add lifecycle machinery solely for architectural symmetry.
|
||||
|
||||
## Additional orchestration concepts
|
||||
|
||||
Queues, concurrency controls, distributed execution, human wait states, scheduling, and workflow status models are all conceivable around transformer operations.
|
||||
|
||||
None belong in Optimus merely because they are imaginable. Introduce only the smallest capability demanded by concrete work when that work arrives.
|
||||
@@ -0,0 +1,105 @@
|
||||
# Intentional Behavior
|
||||
|
||||
This document records Optimus behavior and boundaries that are deliberate. They should not be removed, generalized, centralized, or "cleaned up" without discussion about why they exist.
|
||||
|
||||
## Optimus is a pull framework
|
||||
|
||||
A desired artifact is requested at the top. Modules recursively request what they need. Work wakes up where the requested dependency chain finds missing or stale results.
|
||||
|
||||
Do not replace this with a centrally pushed stage sequence merely because a particular project happens to have a visually linear flow.
|
||||
|
||||
Ordinary module calls are allowed to be the dependency graph. A duplicate declarative DAG is not required.
|
||||
|
||||
A consumer normally establishes another module's artifact by ensuring it. Reading that module's persisted artifact directly in order to suppress a possible rebuild is intentionally not a second dependency mechanism. If an ensure rebuilds work that is not semantically stale, fix the owning transformer's freshness rule.
|
||||
|
||||
If a result is intentionally no longer evergreen, make that break explicit: publish/eject the accepted result and use the exported file as input to a separate project or graph. A frozen handoff and a live Optimus dependency are different concepts.
|
||||
|
||||
## Modules are broader than transformers
|
||||
|
||||
Optimus organizes modules.
|
||||
|
||||
A transformer is a module that can produce an artifact and determine whether an existing artifact remains current according to its own needs. Not every module has to produce artifacts.
|
||||
|
||||
Do not force service modules, human-facing modules, LLM wrappers, publishers, or other legitimate participants into an artificial transformer interface.
|
||||
|
||||
## Peer modules are resolved by semantic name
|
||||
|
||||
`settings/modules.json` is the project's composition map. Peer modules depend on one another by semantic module name and obtain one another through Optimus, normally with `utils.loadModule(name)`.
|
||||
|
||||
A module may freely use relative imports among private files inside its own module directory. It should not import a neighboring peer module by filesystem location. A neighboring directory that provides a real cross-module service should have a registered module identity; implementation that is private to one module should live inside that module instead.
|
||||
|
||||
This boundary is intentional. Optimus is the dependency resolver for peer modules, so consumers do not need to know whether a collaborator currently lives beside them in `src/`, is later extracted, or is otherwise mapped differently by the project. Avoid introducing a second peer-resolution convention based on `../some-module` paths merely because today's checkout makes that path convenient.
|
||||
|
||||
The current runtime reads filesystem entry paths from `settings/modules.json`. That is composition detail owned by the project mapping, not knowledge that should leak into consumers.
|
||||
|
||||
## Transformers may own several related transformations
|
||||
|
||||
Transformer is a responsibility, not a microservice size rule.
|
||||
|
||||
A coherent module may produce multiple artifact types or layers when those transformations genuinely belong together. Avoid both monoliths and artificial fragmentation.
|
||||
|
||||
## Freshness belongs to the transformer
|
||||
|
||||
Optimus supplies reusable mechanisms such as `resolveArtifact()` and `sameSourceHash()`. These make exact named-parent-hash freshness easy.
|
||||
|
||||
They are not the universal semantic definition of stale.
|
||||
|
||||
The owning transformer decides which inputs and rules matter to its output and is responsible for verifying those conditions before returning persisted work as current.
|
||||
|
||||
Do not move domain-specific invalidation policy into Optimus simply to make all transformers look identical.
|
||||
|
||||
Freshness sensitivity is a judgment call owned by the transformer and its pipeline. Cheap deterministic work may intentionally be highly sensitive because reconsideration costs almost nothing. Expensive or nondeterministic work may deliberately use a narrower validity contract. Hash helpers are tools, not requirements to collect every available dependency.
|
||||
|
||||
Artifact boundaries are likewise judgment calls. Granularity is valuable when it creates useful independent stability or clearer organization, but Optimus does not prescribe one artifact per consumer, one artifact per source node, or maximum fragmentation.
|
||||
|
||||
## Content hashes contain propagation
|
||||
|
||||
Children key off parent content identity, not the fact that the parent happened to rerun.
|
||||
|
||||
When a parent is rebuilt from a changed recipe but produces identical semantic content, downstream artifacts may remain current.
|
||||
|
||||
This is intentional and particularly important for expensive or nondeterministic work.
|
||||
|
||||
## Artifact storage is a workbench and warehouse
|
||||
|
||||
Artifact folders are intended to be useful to humans.
|
||||
|
||||
Do not replace readable artifact organization with opaque hash-only cache directories or structures that require special tooling merely to locate a known result.
|
||||
|
||||
Metadata should support provenance and freshness while leaving the actual work discoverable.
|
||||
|
||||
## Artifacts may have many kinds of producers
|
||||
|
||||
An artifact may be produced by deterministic code, an LLM, a human, an imported external source, or a combination.
|
||||
|
||||
Optimus does not require a generic human-task system or LLM subsystem to permit those producers. The responsible module owns the interaction and validity semantics.
|
||||
|
||||
## Side effects do not become semantic inputs automatically
|
||||
|
||||
Reasoning traces, request transcripts, timing, retries, token counts, diagnostics, and progress information can be valuable to keep. They are not semantic dependencies merely because they were generated during the work.
|
||||
|
||||
Do not make semantic artifacts depend on side-effect files unless their content has genuinely become part of the transformation's meaning.
|
||||
|
||||
## Settings are domain-agnostic
|
||||
|
||||
`getSettings(name)` gives Optimus projects a simple shared settings mechanism. Optimus does not interpret arbitrary setting content.
|
||||
|
||||
Do not add schemas, typed configuration domains, or framework ownership of settings that belong to modules without concrete evidence that the simple JSON model has failed.
|
||||
|
||||
## Presentation is reporting only
|
||||
|
||||
Optimus recognizes `presentation.showOnEnsure` and `presentation.showOnBuild`. Missing settings default to quiet ensure checks and visible actual builds. `resolveArtifact()` reports these decisions automatically; custom-validity transformers may call `reportEnsure()` / `reportBuild()` without owning console policy.
|
||||
|
||||
These settings and reporting hooks do not participate in artifact identity, freshness, ancestry, or persistence. Application-owned presentation settings may coexist in the same settings object and are ignored by Optimus.
|
||||
|
||||
`setArtifactOutcome()` remains as a compatibility reporting hook; it is also non-semantic.
|
||||
|
||||
## Module initialization is free
|
||||
|
||||
Current modules are initialized at project startup. A module may use initialization merely for setup or may synchronously establish substantial working state when its real responsibility requires that. Optimus does not impose a "lightweight init" rule.
|
||||
|
||||
Do not introduce lifecycle restrictions, lazy-loading machinery, or async conventions merely to make modules look uniform.
|
||||
|
||||
## 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.
|
||||
@@ -2,6 +2,12 @@ const crypto = require("crypto");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const STATUS_OK = "ok";
|
||||
const STATUS_SUS = "sus";
|
||||
const STATUS_INHERITED_SUS = "inherited-sus";
|
||||
const VALID_STATUSES = new Set([STATUS_OK, STATUS_SUS, STATUS_INHERITED_SUS]);
|
||||
const SUS_RESULT = Symbol("optimus.sus-result");
|
||||
|
||||
function isPlainObject(value) {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -57,10 +63,42 @@ function getSourceHash(sources) {
|
||||
return sourceHash;
|
||||
}
|
||||
|
||||
function buildNode(payload, sources = {}) {
|
||||
function getSourceRef(sources) {
|
||||
const sourceRef = {};
|
||||
for (const [name, source] of Object.entries(sources)) {
|
||||
if (source && typeof source === "object" && source.artifact) sourceRef[name] = source.artifact;
|
||||
}
|
||||
return sourceRef;
|
||||
}
|
||||
|
||||
function statusOf(node) {
|
||||
if (!node || typeof node !== "object" || node.status === undefined) return STATUS_OK;
|
||||
if (!VALID_STATUSES.has(node.status)) throw new Error(`Unknown artifact status: ${JSON.stringify(node.status)}`);
|
||||
return node.status;
|
||||
}
|
||||
|
||||
function inheritedStatus(sources = {}) {
|
||||
return Object.values(sources).some(source => statusOf(source) !== STATUS_OK)
|
||||
? STATUS_INHERITED_SUS
|
||||
: STATUS_OK;
|
||||
}
|
||||
|
||||
function sus(payload) {
|
||||
return { [SUS_RESULT]: true, payload };
|
||||
}
|
||||
|
||||
function unwrapResult(result) {
|
||||
return result && typeof result === "object" && result[SUS_RESULT] === true
|
||||
? { payload: result.payload, localSus: true }
|
||||
: { payload: result, localSus: false };
|
||||
}
|
||||
|
||||
function buildNode(result, sources = {}) {
|
||||
const { payload, localSus } = unwrapResult(result);
|
||||
return {
|
||||
sourceHash: getSourceHash(sources),
|
||||
hash: hashPayload(payload),
|
||||
status: localSus ? STATUS_SUS : inheritedStatus(sources),
|
||||
payload,
|
||||
};
|
||||
}
|
||||
@@ -70,16 +108,131 @@ function buildBinaryNode(filePath, sources = {}) {
|
||||
return {
|
||||
sourceHash: getSourceHash(sources),
|
||||
hash: crypto.createHash("sha256").update(bytes).digest("hex"),
|
||||
status: inheritedStatus(sources),
|
||||
payloadBin: filePath,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
function ensureDir(filename) {
|
||||
fs.mkdirSync(path.dirname(filename), { recursive: true });
|
||||
}
|
||||
|
||||
function writeJsonAtomic(filename, value) {
|
||||
ensureDir(filename);
|
||||
const tempFile = `${filename}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
||||
fs.writeFileSync(tempFile, JSON.stringify(value, null, 2) + "\n", "utf8");
|
||||
try { fs.renameSync(tempFile, filename); }
|
||||
catch (error) {
|
||||
if (!fs.existsSync(filename)) throw error;
|
||||
fs.rmSync(filename, { force: true });
|
||||
fs.renameSync(tempFile, filename);
|
||||
}
|
||||
}
|
||||
|
||||
function readArtifact(filename) {
|
||||
if (!fs.existsSync(filename)) return null;
|
||||
try { return JSON.parse(fs.readFileSync(filename, "utf8")); }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
function sameSourceHash(node, sources = {}) {
|
||||
if (!node || typeof node !== "object" || !node.hash || !node.sourceHash) return false;
|
||||
const expected = getSourceHash(sources);
|
||||
const actualKeys = Object.keys(node.sourceHash).sort();
|
||||
const expectedKeys = Object.keys(expected).sort();
|
||||
return actualKeys.length === expectedKeys.length
|
||||
&& expectedKeys.every((name, index) => name === actualKeys[index] && node.sourceHash[name] === expected[name]);
|
||||
}
|
||||
|
||||
function reconcileArtifactStatus(filename, node, sources = {}) {
|
||||
if (!node || typeof node !== "object") return node;
|
||||
const current = statusOf(node);
|
||||
const expected = current === STATUS_SUS ? STATUS_SUS : inheritedStatus(sources);
|
||||
if (current === expected) return node;
|
||||
const updated = { ...node, status: expected };
|
||||
writeJsonAtomic(filename, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
async function resolveArtifact(filename, sources, producer) {
|
||||
const existing = readArtifact(filename);
|
||||
if (existing && sameSourceHash(existing, sources)) return reconcileArtifactStatus(filename, existing, sources);
|
||||
const result = await producer();
|
||||
const node = buildNode(result, sources);
|
||||
node.artifact = path.relative(process.cwd(), filename).replace(/\\/g, "/");
|
||||
const sourceRef = getSourceRef(sources);
|
||||
if (Object.keys(sourceRef).length > 0) node.sourceRef = sourceRef;
|
||||
writeJsonAtomic(filename, node);
|
||||
return node;
|
||||
}
|
||||
|
||||
function invalidateArtifact(filename) {
|
||||
if (!fs.existsSync(filename)) return false;
|
||||
fs.rmSync(filename, { recursive: true, force: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
function fileNode(filename) {
|
||||
const bytes = fs.readFileSync(filename);
|
||||
const ref = path.relative(process.cwd(), filename).replace(/\\/g, "/");
|
||||
return {
|
||||
artifact: ref,
|
||||
sourceHash: {},
|
||||
hash: crypto.createHash("sha256").update(bytes).digest("hex"),
|
||||
status: STATUS_OK,
|
||||
payload: ref,
|
||||
};
|
||||
}
|
||||
|
||||
function codeNode(label, value) {
|
||||
const code = typeof value === "function" ? value.toString() : String(value);
|
||||
return buildNode({ label, code });
|
||||
}
|
||||
|
||||
function initialize(projectRoot = process.cwd(), options = {}) {
|
||||
const settingOverlays = options.settingOverlays || [];
|
||||
if (!Array.isArray(settingOverlays)) throw new Error("options.settingOverlays must be an array");
|
||||
const settings = loadSettings(projectRoot, settingOverlays);
|
||||
const registry = new Map();
|
||||
let artifactOutcome;
|
||||
let relitigateSus = false;
|
||||
|
||||
const presentation = settings.get("presentation") || {};
|
||||
const showOnEnsure = presentation.showOnEnsure === true;
|
||||
const showOnBuild = presentation.showOnBuild !== false;
|
||||
|
||||
function displayArtifactLabel(value) {
|
||||
if (!value) return "artifact";
|
||||
if (!path.isAbsolute(value)) return String(value);
|
||||
const relative = path.relative(projectRoot, value).replace(/\\/g, "/");
|
||||
return relative || path.basename(value);
|
||||
}
|
||||
|
||||
function reportEnsure(value) {
|
||||
if (showOnEnsure) console.log(`Ensuring artifact: ${displayArtifactLabel(value)}`);
|
||||
}
|
||||
|
||||
function reportBuild(value) {
|
||||
if (showOnBuild) console.log(`Building artifact: ${displayArtifactLabel(value)}`);
|
||||
}
|
||||
|
||||
async function projectResolveArtifact(filename, sources, producer) {
|
||||
reportEnsure(filename);
|
||||
const existing = readArtifact(filename);
|
||||
if (existing && sameSourceHash(existing, sources)) {
|
||||
const reconciled = reconcileArtifactStatus(filename, existing, sources);
|
||||
if (!(relitigateSus && statusOf(reconciled) === STATUS_SUS)) return reconciled;
|
||||
}
|
||||
reportBuild(filename);
|
||||
const result = await producer();
|
||||
const node = buildNode(result, sources);
|
||||
node.artifact = path.relative(process.cwd(), filename).replace(/\\/g, "/");
|
||||
const sourceRef = getSourceRef(sources);
|
||||
if (Object.keys(sourceRef).length > 0) node.sourceRef = sourceRef;
|
||||
writeJsonAtomic(filename, node);
|
||||
return node;
|
||||
}
|
||||
|
||||
const utils = {
|
||||
loadModule(name) {
|
||||
@@ -109,7 +262,23 @@ function initialize(projectRoot = process.cwd(), options = {}) {
|
||||
hashPayload,
|
||||
buildNode,
|
||||
buildBinaryNode,
|
||||
resolveArtifact: projectResolveArtifact,
|
||||
readArtifact,
|
||||
sameSourceHash,
|
||||
statusOf,
|
||||
sus,
|
||||
reconcileArtifactStatus,
|
||||
shouldRelitigateSus(node) {
|
||||
return relitigateSus && statusOf(node) === STATUS_SUS;
|
||||
},
|
||||
invalidateArtifact,
|
||||
fileNode,
|
||||
codeNode,
|
||||
|
||||
// UI/diagnostic reporting only. These must never participate in
|
||||
// artifact identity, validity, ancestry, or dependency resolution.
|
||||
reportEnsure,
|
||||
reportBuild,
|
||||
setArtifactOutcome(value) {
|
||||
artifactOutcome = `${value ?? ""}`.trim() || undefined;
|
||||
},
|
||||
@@ -127,7 +296,8 @@ function initialize(projectRoot = process.cwd(), options = {}) {
|
||||
|
||||
for (const name of registry.keys()) utils.loadModule(name);
|
||||
|
||||
function buildArtifact(name) {
|
||||
function buildArtifact(name, options = {}) {
|
||||
if (!options || typeof options !== "object" || Array.isArray(options)) throw new Error("buildArtifact options must be an object");
|
||||
const artifacts = utils.getSettings("artifacts");
|
||||
const artifact = artifacts[name];
|
||||
if (!artifact) throw new Error(`Unknown artifact: ${name}`);
|
||||
@@ -143,36 +313,43 @@ function initialize(projectRoot = process.cwd(), options = {}) {
|
||||
const params = artifact.params === undefined ? [] : artifact.params;
|
||||
if (!Array.isArray(params)) throw new Error(`Artifact "${name}" params must be an array`);
|
||||
|
||||
const previousRelitigateSus = relitigateSus;
|
||||
relitigateSus = previousRelitigateSus || options.relitigateSus === true;
|
||||
artifactOutcome = undefined;
|
||||
console.log(`Ensuring artifact: ${name}`);
|
||||
reportEnsure(name);
|
||||
const restore = () => { relitigateSus = previousRelitigateSus; };
|
||||
try {
|
||||
const result = builder(...params);
|
||||
if (result && typeof result.then === "function") {
|
||||
return result.then(value => {
|
||||
console.log(` ${artifactOutcome ?? "completed — success"}`);
|
||||
if (showOnEnsure && artifactOutcome) console.log(` ${artifactOutcome}`);
|
||||
artifactOutcome = undefined;
|
||||
restore();
|
||||
return value;
|
||||
}, error => {
|
||||
console.error(" failed");
|
||||
console.error(`Artifact failed: ${name}`);
|
||||
artifactOutcome = undefined;
|
||||
restore();
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
|
||||
console.log(` ${artifactOutcome ?? "completed — success"}`);
|
||||
if (showOnEnsure && artifactOutcome) console.log(` ${artifactOutcome}`);
|
||||
artifactOutcome = undefined;
|
||||
restore();
|
||||
return result;
|
||||
}
|
||||
catch (error) {
|
||||
console.error(" failed");
|
||||
console.error(`Artifact failed: ${name}`);
|
||||
artifactOutcome = undefined;
|
||||
restore();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function buildAll() {
|
||||
async function buildAll(options = {}) {
|
||||
const artifacts = utils.getSettings("artifacts");
|
||||
for (const name of Object.keys(artifacts)) await buildArtifact(name);
|
||||
for (const name of Object.keys(artifacts)) await buildArtifact(name, options);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -182,10 +359,33 @@ function initialize(projectRoot = process.cwd(), options = {}) {
|
||||
hashPayload,
|
||||
buildNode,
|
||||
buildBinaryNode,
|
||||
resolveArtifact: projectResolveArtifact,
|
||||
readArtifact,
|
||||
sameSourceHash,
|
||||
statusOf,
|
||||
sus,
|
||||
reconcileArtifactStatus,
|
||||
invalidateArtifact,
|
||||
fileNode,
|
||||
codeNode,
|
||||
buildArtifact,
|
||||
buildAll,
|
||||
modules: [...registry.keys()],
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { initialize, hashPayload, buildNode, buildBinaryNode };
|
||||
module.exports = {
|
||||
initialize,
|
||||
hashPayload,
|
||||
buildNode,
|
||||
buildBinaryNode,
|
||||
resolveArtifact,
|
||||
readArtifact,
|
||||
sameSourceHash,
|
||||
statusOf,
|
||||
sus,
|
||||
reconcileArtifactStatus,
|
||||
invalidateArtifact,
|
||||
fileNode,
|
||||
codeNode,
|
||||
};
|
||||
|
||||
BIN
Binary file not shown.
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "optimus",
|
||||
"version": "0.3.0",
|
||||
"version": "0.5.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "optimus",
|
||||
"version": "0.3.0",
|
||||
"version": "0.5.1",
|
||||
"license": "UNLICENSED",
|
||||
"bin": {
|
||||
"optimus": "bin/optimus.js"
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "optimus",
|
||||
"version": "0.5.0",
|
||||
"version": "0.5.1",
|
||||
"description": "Minimal project runtime for initialized modules, settings, artifacts, and transformer nodes. Optimal transformation pipeline foreman.",
|
||||
"main": "index.js",
|
||||
"bin": {
|
||||
@@ -14,5 +14,5 @@
|
||||
"scripts": {
|
||||
"test": "node test/smoke.js"
|
||||
},
|
||||
"license": "UNLICENSED"
|
||||
"license": "BSD-3-Clause"
|
||||
}
|
||||
|
||||
+213
-2
@@ -40,6 +40,7 @@ async function main() {
|
||||
const node = buildNode({ result: true }, { source });
|
||||
assert.deepStrictEqual(node.sourceHash, { source: source.hash });
|
||||
assert.strictEqual(node.hash, hashPayload(node.payload));
|
||||
assert.strictEqual(node.status, "ok");
|
||||
assert.deepStrictEqual(node.payload, { result: true });
|
||||
|
||||
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "optimus-binary-"));
|
||||
@@ -53,6 +54,7 @@ async function main() {
|
||||
const expectedBinaryHash = crypto.createHash("sha256").update(firstBytes).digest("hex");
|
||||
assert.deepStrictEqual(binaryNode.sourceHash, { source: source.hash });
|
||||
assert.strictEqual(binaryNode.hash, expectedBinaryHash);
|
||||
assert.strictEqual(binaryNode.status, "ok");
|
||||
assert.strictEqual(binaryNode.payloadBin, binaryPath);
|
||||
assert.strictEqual("payload" in binaryNode, false);
|
||||
|
||||
@@ -67,14 +69,223 @@ async function main() {
|
||||
fs.rmSync(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
const artifact = optimus.buildArtifact("beta-demo");
|
||||
assert.strictEqual(typeof artifact?.then, "undefined");
|
||||
const durableRoot = fs.mkdtempSync(path.join(os.tmpdir(), "optimus-durable-"));
|
||||
try {
|
||||
const artifactFile = path.join(durableRoot, "result.json");
|
||||
let builds = 0;
|
||||
const parentA = buildNode("same-parent-content", { recipe: buildNode("recipe-a") });
|
||||
const firstDurable = await optimus.resolveArtifact(artifactFile, { parent: parentA }, async () => { builds++; return "result"; });
|
||||
const secondDurable = await optimus.resolveArtifact(artifactFile, { parent: parentA }, async () => { builds++; return "should-not-run"; });
|
||||
assert.strictEqual(builds, 1);
|
||||
assert.strictEqual(firstDurable.hash, secondDurable.hash);
|
||||
assert.ok(secondDurable.artifact);
|
||||
|
||||
// A parent may be regenerated from a different recipe yet keep identical content.
|
||||
// Children key off the parent's content hash, so no downstream rebuild occurs.
|
||||
const parentB = buildNode("same-parent-content", { recipe: buildNode("recipe-b") });
|
||||
assert.strictEqual(parentA.hash, parentB.hash);
|
||||
await optimus.resolveArtifact(artifactFile, { parent: parentB }, async () => { builds++; return "should-still-not-run"; });
|
||||
assert.strictEqual(builds, 1);
|
||||
|
||||
// Changing the complete named parent set is a different recipe.
|
||||
await optimus.resolveArtifact(artifactFile, { parent: parentB, thirdWitness: buildNode("new") }, async () => { builds++; return "result"; });
|
||||
assert.strictEqual(builds, 2);
|
||||
|
||||
assert.strictEqual(optimus.invalidateArtifact(artifactFile), true);
|
||||
assert.strictEqual(fs.existsSync(artifactFile), false);
|
||||
} finally {
|
||||
fs.rmSync(durableRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
// Suspicion is durable but does not block downstream work. Local `sus`
|
||||
// must be relitigated; inherited suspicion is recalculated from every
|
||||
// current parent and can clear without rerunning an unchanged transformer.
|
||||
const susRoot = fs.mkdtempSync(path.join(os.tmpdir(), "optimus-sus-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(susRoot, "settings"), { recursive: true });
|
||||
fs.mkdirSync(path.join(susRoot, "src", "worker"), { recursive: true });
|
||||
fs.writeFileSync(path.join(susRoot, "settings", "modules.json"), JSON.stringify({ worker: "./src/worker/index.js" }));
|
||||
fs.writeFileSync(path.join(susRoot, "settings", "artifacts.json"), JSON.stringify({ target: { module: "worker", builder: "buildTarget" } }));
|
||||
fs.writeFileSync(path.join(susRoot, "settings", "presentation.json"), JSON.stringify({ showOnEnsure: false, showOnBuild: false }));
|
||||
fs.writeFileSync(path.join(susRoot, "state.json"), JSON.stringify({ aSus: true, bSus: true, childSus: false, aPayload: "a", bPayload: "b" }));
|
||||
fs.writeFileSync(path.join(susRoot, "counts.json"), JSON.stringify({}));
|
||||
fs.writeFileSync(path.join(susRoot, "src", "worker", "index.js"), `const fs = require("fs");
|
||||
const path = require("path");
|
||||
module.exports = utils => {
|
||||
const root = ${JSON.stringify(susRoot)};
|
||||
const artifact = name => path.join(root, "artifacts", name + ".json");
|
||||
const state = () => JSON.parse(fs.readFileSync(path.join(root, "state.json"), "utf8"));
|
||||
const bump = name => {
|
||||
const filename = path.join(root, "counts.json");
|
||||
const counts = JSON.parse(fs.readFileSync(filename, "utf8"));
|
||||
counts[name] = (counts[name] || 0) + 1;
|
||||
fs.writeFileSync(filename, JSON.stringify(counts));
|
||||
};
|
||||
async function ensureA() {
|
||||
return utils.resolveArtifact(artifact("a"), {}, async () => {
|
||||
bump("a");
|
||||
const current = state();
|
||||
return current.aSus ? utils.sus(current.aPayload) : current.aPayload;
|
||||
});
|
||||
}
|
||||
async function ensureB() {
|
||||
return utils.resolveArtifact(artifact("b"), {}, async () => {
|
||||
bump("b");
|
||||
const current = state();
|
||||
return current.bSus ? utils.sus(current.bPayload) : current.bPayload;
|
||||
});
|
||||
}
|
||||
async function ensureChild() {
|
||||
const a = await ensureA();
|
||||
const b = await ensureB();
|
||||
return utils.resolveArtifact(artifact("child"), { a, b }, async () => {
|
||||
bump("child");
|
||||
const payload = "child:" + a.payload + ":" + b.payload;
|
||||
return state().childSus ? utils.sus(payload) : payload;
|
||||
});
|
||||
}
|
||||
async function buildTarget() {
|
||||
const child = await ensureChild();
|
||||
return utils.resolveArtifact(artifact("target"), { child }, async () => {
|
||||
bump("target");
|
||||
return "target:" + child.payload;
|
||||
});
|
||||
}
|
||||
return { buildTarget };
|
||||
};\n`);
|
||||
|
||||
const runtime = initialize(susRoot);
|
||||
const readNode = name => JSON.parse(fs.readFileSync(path.join(susRoot, "artifacts", `${name}.json`), "utf8"));
|
||||
const readCounts = () => JSON.parse(fs.readFileSync(path.join(susRoot, "counts.json"), "utf8"));
|
||||
const writeState = patch => {
|
||||
const filename = path.join(susRoot, "state.json");
|
||||
fs.writeFileSync(filename, JSON.stringify({ ...JSON.parse(fs.readFileSync(filename, "utf8")), ...patch }));
|
||||
};
|
||||
|
||||
await runtime.buildArtifact("target");
|
||||
assert.strictEqual(readNode("a").status, "sus");
|
||||
assert.strictEqual(readNode("b").status, "sus");
|
||||
assert.strictEqual(readNode("child").status, "inherited-sus");
|
||||
assert.strictEqual(readNode("target").status, "inherited-sus");
|
||||
assert.deepStrictEqual(readCounts(), { a: 1, b: 1, child: 1, target: 1 });
|
||||
|
||||
// Repairing only one of two suspicious parents must not clear the child.
|
||||
writeState({ aSus: false });
|
||||
await runtime.buildArtifact("target", { relitigateSus: true });
|
||||
assert.strictEqual(readNode("a").status, "ok");
|
||||
assert.strictEqual(readNode("b").status, "sus");
|
||||
assert.strictEqual(readNode("child").status, "inherited-sus");
|
||||
assert.deepStrictEqual(readCounts(), { a: 2, b: 2, child: 1, target: 1 });
|
||||
|
||||
// Once the last suspicious parent clears with the same payload, inherited
|
||||
// descendants clear too, without semantic transformer reruns.
|
||||
writeState({ bSus: false });
|
||||
await runtime.buildArtifact("target", { relitigateSus: true });
|
||||
assert.strictEqual(readNode("b").status, "ok");
|
||||
assert.strictEqual(readNode("child").status, "ok");
|
||||
assert.strictEqual(readNode("target").status, "ok");
|
||||
assert.deepStrictEqual(readCounts(), { a: 2, b: 3, child: 1, target: 1 });
|
||||
|
||||
// Local sus never clears merely because its parents are clean. It requires
|
||||
// relitigation of that artifact itself.
|
||||
fs.rmSync(path.join(susRoot, "artifacts", "child.json"), { force: true });
|
||||
fs.rmSync(path.join(susRoot, "artifacts", "target.json"), { force: true });
|
||||
writeState({ childSus: true });
|
||||
await runtime.buildArtifact("target");
|
||||
assert.strictEqual(readNode("child").status, "sus");
|
||||
assert.strictEqual(readNode("target").status, "inherited-sus");
|
||||
const beforeLocalRepair = readCounts();
|
||||
|
||||
writeState({ childSus: false });
|
||||
await runtime.buildArtifact("target");
|
||||
assert.strictEqual(readNode("child").status, "sus");
|
||||
assert.deepStrictEqual(readCounts(), beforeLocalRepair, "ordinary ensure must reuse local sus rather than silently retry it");
|
||||
|
||||
await runtime.buildArtifact("target", { relitigateSus: true });
|
||||
assert.strictEqual(readNode("child").status, "ok");
|
||||
assert.strictEqual(readNode("target").status, "ok");
|
||||
const afterLocalRepair = readCounts();
|
||||
assert.strictEqual(afterLocalRepair.child, beforeLocalRepair.child + 1);
|
||||
assert.strictEqual(afterLocalRepair.target, beforeLocalRepair.target, "status-only repair must not rerun an unchanged descendant");
|
||||
} finally {
|
||||
fs.rmSync(susRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
const artifact = await optimus.buildArtifact("beta-demo");
|
||||
assert.deepStrictEqual(artifact.sourceHash, { alpha: optimus.loadModule("alpha").loadAlpha("demo").hash });
|
||||
assert.strictEqual(artifact.payload, "beta:alpha:demo");
|
||||
|
||||
const all = await optimus.buildAll();
|
||||
assert.strictEqual(all, undefined);
|
||||
|
||||
// setArtifactOutcome is a retained reporting compatibility API. It affects
|
||||
// only buildArtifact() console status and never artifact validity.
|
||||
const outcomeRoot = fs.mkdtempSync(path.join(os.tmpdir(), "optimus-outcome-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(outcomeRoot, "settings"), { recursive: true });
|
||||
fs.mkdirSync(path.join(outcomeRoot, "src", "reporter"), { recursive: true });
|
||||
fs.writeFileSync(path.join(outcomeRoot, "settings", "modules.json"), JSON.stringify({ reporter: "./src/reporter/index.js" }));
|
||||
fs.writeFileSync(path.join(outcomeRoot, "settings", "artifacts.json"), JSON.stringify({ report: { module: "reporter", builder: "buildReport" } }));
|
||||
fs.writeFileSync(path.join(outcomeRoot, "settings", "presentation.json"), JSON.stringify({ showOnEnsure: true, showOnBuild: false }));
|
||||
fs.writeFileSync(path.join(outcomeRoot, "src", "reporter", "index.js"), `module.exports = utils => ({
|
||||
buildReport() {
|
||||
utils.setArtifactOutcome("up to date");
|
||||
return utils.buildNode("report");
|
||||
}
|
||||
});\n`);
|
||||
|
||||
const reporting = initialize(outcomeRoot);
|
||||
assert.strictEqual(typeof reporting.utils.setArtifactOutcome, "function");
|
||||
const messages = [];
|
||||
const originalLog = console.log;
|
||||
console.log = (...args) => messages.push(args.join(" "));
|
||||
try {
|
||||
await reporting.buildArtifact("report");
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
}
|
||||
assert.ok(messages.some(message => message === "Ensuring artifact: report"));
|
||||
assert.ok(messages.some(message => message.trim() === "up to date"));
|
||||
} finally {
|
||||
fs.rmSync(outcomeRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
|
||||
// Presentation defaults are quiet on ensure and visible on actual build.
|
||||
// The settings are reporting only and do not affect artifact semantics.
|
||||
const presentationRoot = fs.mkdtempSync(path.join(os.tmpdir(), "optimus-presentation-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(presentationRoot, "settings"), { recursive: true });
|
||||
fs.mkdirSync(path.join(presentationRoot, "src", "worker"), { recursive: true });
|
||||
fs.writeFileSync(path.join(presentationRoot, "settings", "modules.json"), JSON.stringify({ worker: "./src/worker/index.js" }));
|
||||
fs.writeFileSync(path.join(presentationRoot, "settings", "artifacts.json"), JSON.stringify({ demo: { module: "worker", builder: "buildDemo" } }));
|
||||
fs.writeFileSync(path.join(presentationRoot, "src", "worker", "index.js"), `const path = require("path");
|
||||
module.exports = utils => ({
|
||||
buildDemo() {
|
||||
return utils.resolveArtifact(path.join(${JSON.stringify(presentationRoot)}, "artifacts", "worker", "demo.json"), {}, async () => "demo");
|
||||
}
|
||||
});\n`);
|
||||
|
||||
const messages = [];
|
||||
const originalLog = console.log;
|
||||
console.log = (...args) => messages.push(args.join(" "));
|
||||
try {
|
||||
const runtime = initialize(presentationRoot);
|
||||
await runtime.buildArtifact("demo");
|
||||
assert.ok(messages.some(message => message === "Building artifact: artifacts/worker/demo.json"));
|
||||
assert.ok(!messages.some(message => message.startsWith("Ensuring artifact:")));
|
||||
|
||||
messages.length = 0;
|
||||
await runtime.buildArtifact("demo");
|
||||
assert.ok(!messages.some(message => message.startsWith("Building artifact:")));
|
||||
assert.ok(!messages.some(message => message.startsWith("Ensuring artifact:")));
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(presentationRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
console.log("smoke test passed");
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user