Engineering guidance for all contributors, including autonomous coding agents.
CONTRIBUTING.md is the canonical contribution policy. SolverForge is explicitly pro-AI and pro-agent, uses AI in its own development, and welcomes AI-assisted and fully agent-generated work.
- Evaluate contributions on correctness, quality, maintainability, architecture and style fit, tests, and project benefit. Do not use authorship or tool origin as an acceptance or rejection criterion.
- Agents may submit pull requests and review contributions. Maintainers retain responsibility for merge decisions.
- Understand the final diff, verify behavior, and address review findings. Report actual verification commands and results, including relevant checks that were not run. Do not present an agent's assurance as verification.
- AI disclosure is optional. Do not require tool declarations, human-only submission or review, or special restrictions on LLM use in code, docs, comments, or issues beyond ordinary quality, conduct, and legal standards.
- Enforce quality through review, automation, and selective merging rather than tool bans. AI-assisted review, summarization, and triage are welcome.
SolverForge is a high-performance heuristic constraint programming framework in Rust for planning and scheduling problems.
Workspace structure:
solverforge (facade + re-exports)
|
|-- solverforge-solver - Phases, moves, selectors, termination, SolverManager
|-- solverforge-scoring - ConstraintStream API, SERIO incremental scoring
|-- solverforge-config - TOML configuration
|-- solverforge-bridge - Dynamic host-language binding contracts
|-- solverforge-console - Tracing-driven console output and progress formatting
|-- solverforge-cvrp - CVRP profile helpers, traits, meters, and hook bundles
|-- solverforge-macros - planning_model!, #[planning_solution], #[planning_entity], #[problem_fact]
|
`-> solverforge-core - Score types, domain traits, descriptors
Publishing runs only in the Release workflow (.github/workflows/release.yml,
see RELEASE.md); cargo derives the upload order from the crates' dependencies,
so the order is not listed anywhere by hand.
Standalone ecosystem repos such as solverforge-cli, solverforge-ui, and solverforge-maps are not part of this workspace. Treat references to them as external integrations, not in-repo crates.
Current workspace release version: 0.32.0.
Use README.md, the user guides under docs/, crate manifests, and the crate wireframes to confirm current details before changing public APIs.
Canonical generated domains use solverforge::planning_model! in
src/domain/mod.rs as the model-owned metadata manifest. Entity, fact, and
solution files remain normal separate Rust modules listed in that manifest.
Model ordered sequences and routes with planning list variables. List owners
store Vec<usize> element indexes, while configured inverse, index, previous,
next, custom, cascading, and piggyback shadows remain derived state. Ordinary
scalar construction and local search stay on their direct single-slot mutation
path; do not introduce compound or batch mutation solely to emulate sequence
topology in a scalar field.
Treat the repository documentation as a coordinated surface, not as isolated files.
README.mdis the user-facing entry point and stays short. Keep the first screen oriented to a first-time human user: what SolverForge is, when to use it, how to try it withsolverforge-cli, and where to go next. Below that it carries one constraint example, a feature summary, the documentation map (including the coding-agent pointers), examples, and the Architecture section with theassets/solverforge-architecture.svgdiagram, the crate table and the SERIO image. Feature reference belongs in the user guides, not the README. Do not turn the README into a long release-history dump; useCHANGELOG.mdfor release history andRELEASE.mdfor maintainer release operations.- The user guides
docs/modeling.md,docs/constraints.md,docs/configuration.md,docs/running-solves.mdanddocs/performance.mdhold the feature reference the README links to, one topic each. Put a new user-facing feature in the guide for its topic and keep the README documentation map in step when a guide is added or renamed. - Every ```rust block in the README and in those user guides is compiled:
crates/solverforge/tests/readme_examples.rslists the documents and fails unless each block is checked in verbatim between `// readme:begin` and `// readme:end` under `crates/solverforge/tests/readme_examples/`, so add or edit a block there in the same change. A new user guide is added to that list. crates/*/README.mdis each published crate's crates.io page: one paragraph on what the crate is, pointing applications at thesolverforgefacade. The facade's page is the rootREADME.md. Every published crate also packagesLICENSE(a symlink to the root file), andmake publish-crates-dryfails on amanifest has nopackaging warning.CONTRIBUTING.mdowns the contribution policy. Keep README contribution guidance, agent instructions, and pull request templates consistent with it; do not introduce separate AI acceptance rules on those surfaces.crates/*/WIREFRAME.mdfiles are the canonical public API maps. Update them for any public surface change.- The other
docs/*.mdfiles (extend-*.md) capture focused extension guidance for APIs that are meant to be extended, plus narrowly scoped agent notes that do not belong in this file or in crate wireframes. Do not add standalone contract, charter, audit, or historical plan documents underdocs/; current public APIs belong in the user guides and matching wireframes, while durable repository rules belong here. docs/architecture.htmlis the generated system wiring map (crates, configuration, solve pipeline, runtime anatomy, consumers). Edit its vector source atassets/solverforge-architecture.svgand page layout atscripts/solverforge-architecture.js, then regenerate with Node in the same change as any structural shift they depict. Do not hand-edit the generated HTML or commit raster exports.AGENTS.mdrecords repository-specific rules for future coding agents. Update it when the engineering workflow or documentation policy changes.- Documentation must describe the current checked-in code and public surface, not an intended future design. If a refactor is incomplete, document the shipped boundary and current limitation explicitly instead of documenting the target state as if it already exists.
- Distinguish crate-root re-exports from module-level exports and hidden
__internalbridges. Do not document a module-only or macro-only symbol as if it were a supported root-level facade export.
Each crate has a WIREFRAME.md file that documents its public API surface, module map, and usage patterns. Treat the relevant wireframe as the canonical reference before changing a crate.
Current wireframes:
crates/solverforge/WIREFRAME.mdcrates/solverforge-bridge/WIREFRAME.mdcrates/solverforge-core/WIREFRAME.mdcrates/solverforge-macros/WIREFRAME.mdcrates/solverforge-scoring/WIREFRAME.mdcrates/solverforge-solver/WIREFRAME.mdcrates/solverforge-config/WIREFRAME.mdcrates/solverforge-console/WIREFRAME.mdcrates/solverforge-cvrp/WIREFRAME.md
When public surface changes, update the matching wireframe in the same change:
- Add new public types, traits, functions, and modules.
- Update renamed items and changed signatures.
- Remove deleted public items completely.
- Keep file maps in sync with added or moved files.
- Document public surface and usage only, not implementation detail.
make doc-names (also run by the CI Docs job) fails when a wireframe or a
docs/ guide names, in inline code, a type or function that no longer exists
in crates/*/src; when a wireframe file map lists a missing file; and when a
wireframe leaves out an item of its crate's public-api.txt. Example code
belongs in fenced blocks, which the check skips.
make public-api (in make lint, make pre-release and the CI Docs job)
fails when the rustdoc-visible API of solverforge-core, solverforge-scoring
or solverforge-solver differs from crates/<crate>/public-api.txt. A change
that adds, removes or changes a public item regenerates that snapshot with
python3 scripts/check-public-api.py --bless in the same commit, so review
sees the surface change. Inside those crates, pub means supported surface:
unreachable_pub = "warn" is set in their Cargo [lints] tables, implementation modules are private, and
solverforge-solver exports every supported item once, at its root.
When a public API change also affects how users discover or reason about the
feature, update the corresponding top-level docs in the same change. Extension
point changes should leave a clear trail in the relevant user guide, the
relevant extension guide under docs/, and the affected wireframes, plus
README.md when the feature summary or documentation map changes.
Version bumps are documentation changes too. When the published version changes, update the manifest version plus the coordinated public docs surface in the same change:
Cargo.tomlworkspace version and the exact (=x.y.z) inter-crate dependency versions in every crate manifest, which csemver's postbump moves togetherREADME.md(status line and install snippet)docs/running-solves.md(console banner)AGENTS.md- affected
crates/*/WIREFRAME.mdfiles
All hot-path code must stay monomorphized.
- Do not introduce
Box<dyn Trait>in hot paths. - Do not introduce
Arc<T>orRc<T>. - Do not introduce
dyn Traitunless it is an existing intentional boundary. - Avoid
.clone()in move evaluation and scoring paths. Scoring streams do not requireCloneon entity types, so generic scoring code cannot clone an entity; do not add aClonebound to make one compile. Constraint analysis describes an entity by its type name,Debugrendering and source-rendered planning id (EntityRef) and keeps no copy of it; planning ids are read only on the cold explanation path. - Preserve concrete types through the full solver pipeline.
Intentional type-erasure boundaries that should not be "fixed":
EntityExtractorinsolverforge-core: runtime-erasedSolutionDescriptoraccess only. Canonical generatedRuntimeModeland scoring-stream paths retain concrete collection types.DynamicScalarAccess,DynamicListAccess,DynamicListMetadata, andDynamicScalarAssignmentMetadata: host-language dynamic-model slot boundaries only.RuntimeCandidateMetric: explicit configured host metric boundary forSortedandProbabilisticselector ordering only.RuntimeHostCompoundProviderinbuilder/context/provider: host-language callbacks only. Static Rust candidate and repair providers must stay on their concrete function-pointer and typed-ScalarEditpath.RuntimeHostProviderErrorBoundaryinbuilder/context/provider: cold conversion of core normalization failures into native host exceptions only.ProblemChange::apply(self: Box<Self>, &mut dyn Director<S>)and the per-jobBox<dyn ProblemChange<S>>queue: real-time problem-change integration boundary only. A pending change is a bit in the job's existing control word, next to the pause bit, so safe points observe pause and changes with the single atomic load they already take; decode a non-zero word out of line, and never add a separate poll or drain the queue from a hot loop.SolverPanicPayload: cold preservation of a foreign runtime panic object alongside its stable display message only.
Moves are never cloned in the solver path. Selector cursors own discovered
candidates behind stable CandidateIds; foragers retain IDs, and the selected
move is taken from its cursor by ownership.
Search phases evaluate borrowable candidates by stable ID and materialize
exactly the selected winner by ownership. Construction likewise has one cursor
path per placement; do not add a second eager placement collector or a fallback
move vector. Do not reintroduce owned open_cursor() streams for cartesian
composition.
Clone is acceptable only for:
- Solution snapshots sent through channels.
- Parallel search creating worker-private solution copies: partitioned search's partition copies, and parallel local-search evaluation's evaluator replicas — one working-solution copy per evaluator beyond the main director, made at phase start and again after the working solution is written outside the parallel loop's own commits. Replicas borrow the solve's descriptor; they never copy it.
- Explicit user-owned result snapshots outside retained scoring state, such as
CollectedVec::to_vec()when the caller deliberately asks for an ownedVec<T>.
Grouped collectors own extracted values. Accumulator::accumulate(value) takes
the mapped value by ownership and returns a retraction token; grouped,
cross-grouped, projected-grouped, complemented-grouped, and projected
complemented-grouped constraints cache that token for exact retraction after
entity mutation. Do not restore a borrowed accumulate(&value) /
retract(&value) protocol, and do not require Copy, Clone, or PartialEq
for payloads solely so collect_vec can retain them. collect_vec returns a
CollectedVec<T> result view, not an owned Vec<T> scoring result.
Constraint-stream node sharing belongs in the #[solverforge_constraints]
compiler and the shared grouped node-state engine. Do not implement sharing as
ad hoc runtime caches, global memoization, interior-mutability shortcuts, or
public share/derive modeling APIs.
- The common operator tree (
stream/relational/operator) owns join, filter, flatten, existence, projection, group, and complement row state. Every family's retention is a concrete operator composition, not a bespoke per-family engine. - Shared grouped, projected grouped, and cross grouped nodes keep the shared
accumulator state and the compiler-owned terminal sharing; terminal scorers
remain independent for identity, ordering, metadata, and explanation. A
grouped terminal exposes chained
penalize/rewardso the compiler can build several terminals from one grouped owner. - Grouped join retention composes the common operator tree with that shared accumulator layer rather than re-implementing per-family pair indexing.
Low-level joined filter traits receive the semantic source indexes for the rows being tested. Do not replace them with placeholder values in builders, finalizers, or grouped/projection paths.
- Self-join
BiFilter/TriFilter/QuadFilter/PentaFilterindexes are the same-source entity indexes in canonical tuple order. - Cross-bi filters use the left and right source slice indexes.
- Flattened-bi filters use the A source index and the owning B source index for the flattened C row.
- Projected-bi filters use the projected row's primary owner entity index; row
orientation is still determined by
RowCoordinate, and retained storage row IDs are never semantic. - Public fluent
.filter(...)methods stay entity/value-only and adapt to the indexed trait shape internally.
Compiled solves enumerate candidates through these production loops, and the
selector-cursor zero-regression gate
(crates/solverforge-solver/benches/selector_cursor_gate.rs, run by
scripts/bench-zero-regression.sh) drives each of them through
CompiledRuntimeRunner::compile, the same compilation a configured solve
runs:
- The local-search composition cursor (
SelectorCompositionBorrowedCursoroverRuntimeNeighborhoodState, whichRuntimeNeighborhoodFlatCursorandRuntimeNeighborhoodLeafCursorschedule), including its union and Cartesian compositions. - The compiled list leaf
RuntimeListNeighborhoodCursor(list change, swap, nearby change and swap, sublist change and swap, and k-opt) over the sharedlist_kernelemitters. - The scalar neighborhood leaf
RuntimeScalarNeighborhoodCursor(change, swap and ruin/recreate). - The descriptor-placement scalar construction placer
(
RuntimeScalarConstructionPlacer) and the compiled runtime phase runner that solves first-fit construction. - Grouped-scalar required construction (
assignment_required): the default runtime's required cursor over an assignment group with capacity, sequence and rule keys, solved through the compiled runtime runner; and the compiled grouped-scalar local-search neighborhood of the same group (assignment_neighborhood), including its augmenting-path repairs. - Route moves executed against a scored model: the score director's
cascading list-shadow row maintenance (
route_rows), and grouped list ruin-and-recreate with joint placement of each element group (group_ruin), each candidate done, scored and undone.
The standalone heuristic/selector selectors, decorators, and
QueuedEntityPlacer are test oracles only; no production path runs them.
- Preserve canonical enumeration order. Seeded order drift is a regression.
- Generated moves from finite selectors must remain
is_doable. - Cartesian selectors must keep preview-safe left-child validation, selector-order tabu composition, and borrowable sequential candidates.
- Benchmark touched neighborhood families in release mode before and after refactors with
make bench-zero-regression; add a gate case when a production neighborhood loop has none. - Shared helpers are acceptable for selected-entity snapshots, candidate ordering, and exact
size()accounting, but keepopen_cursor()loops explicit when abstraction hurts throughput or clarity. - Do not accept a median throughput regression greater than 5% without explicit user approval.
element_owner_fn is a partial fixed-owner restriction. Raw hook return values
are interpreted only in solverforge-solver/src/list_placement.rs: absent hook
and hook-returned None mean unrestricted, a valid Some(owner) means fixed to
that owner, and an out-of-range Some(owner) is invalid. Construction,
ruin/recreate, Clarke-Wright, and owner-changing list selectors consume that
shared restriction relation rather than branching on hook presence.
The stock #[planning_list_variable(domain = "cvrp")] profile expands to CVRP
distance meters, VrpSolution, route hooks, savings hooks, and
savings_metric_class. Do not collapse the route-local and construction hook
semantics:
route_hooks::feasible/route_feasibleare strict route-local gates and must reject structurally invalid, over-capacity, and time-window-infeasible routes before route-local phases such asListKOptcommit a reversal.savings_hooks::feasible/savings_feasibleare Clarke-Wright construction admissibility gates and should reject only routes that cannot be evaluated safely by stock CVRP data. Capacity and time-window violations remain scoreable during construction.- Custom routing domains should omit
domain = "cvrp"and provide explicitroute_hooks/savings_hooks; do not add compatibility aliases around the profile defaults.
Use rayon for CPU-bound work and tokio for async coordination.
- Prefer
rayon::spawn,rayon::scope, and parallel iterators. - Use
tokio::sync::mpscfor ownership transfer across async boundaries. - Do not add
std::thread::spawn. - Do not add
std::thread::sleep. - Prefer ownership transfer over callback APIs that only expose
&Self. - Parallel local-search evaluation runs one fork-join (
rayon::joinplus a parallel iterator over the replicas) per evaluation window on the solve thread's current pool. Fork-join jobs live on the stack, so window dispatch allocates nothing; do not reintroduce per-window spawned tasks, dedicated pools, or blocking waits inside evaluation workers.
Configured time, step, move, score-calculation, and phase limits remain binding
during all construction work. Required scalar or list construction is not an
exemption. The compiled runtime owns the structural completion gate: every list
element, required assignment row, and non-optional scalar row must be assigned
before local search, best-solution publication, snapshots, or completed output.
If configured termination is reached first, use the existing Failed lifecycle;
do not add a second status, publish a partial solution, or rely on a watchdog.
For phantom type parameters, prefer PhantomData<fn() -> T> rather than PhantomData<T> so the phantom does not inherit unnecessary Send, Sync, or Clone bounds.
Avoid #[derive(Clone)] on generic types when it would introduce unnecessary bounds. Write a manual Clone impl that only constrains fields that actually need cloning.
- Keep every
mod.rsandlib.rslimited to module declarations andusere-exports: no functions, types, impls, constants, macro definitions, inline module bodies or crate-level attributes.planning_model!manifests and the proc-macro entry points Rust requires insolverforge-macros/src/lib.rsare the only exceptions; lint levels live in each crate's Cargo[lints]table. - Crate roots document the crate with inner
//!doc comments and public items use///(or/** */); plain//and/* */comments never replace them. docs.rs renders only doc comments, so a comment-style sweep must leave them in place. Every crate in the workspace (solverforge,solverforge-core,solverforge-config,solverforge-scoring,solverforge-solver,solverforge-console,solverforge-macros,solverforge-bridgeandsolverforge-cvrp) warns onmissing_docsthrough its Cargo[lints]table, which also covers its integration tests, so every new public item, test crate root and test fixture needs a doc comment. - Move implementation code into dedicated files.
- Keep Rust source and test files under 500 LOC. When a module grows beyond
that boundary, split it by subsystem or behavior into adjacent implementation
files and keep the public module entrypoint small.
make file-length(inmake lint,make pre-releaseand the CI Docs job) fails on any*.rsfile undercrates/orexamples/longer than 500 lines. - The
solverforgefacade is the single dependency: every type a facade item's signature uses must be importable fromsolverforge(a root re-export or one of its layer modules).make facade-reachability(inmake lint,make pre-releaseand the CI Docs job) checks the facade rustdoc for links into other crates. - Prefer doctests for public APIs when practical, and make them compile meaningfully.
- Keep examples and scaffold-facing guidance on the public fluent API surface. If an example requires internal wiring, improve the public API instead.
- Canonical multi-file move and selector behavior tests belong under subsystem
tests/trees. Do not reintroduce parallel*_tests.rssiblings once coverage has been consolidated. - When selector or construction behavior changes, update the dedicated
tests/tree for that subsystem instead of adding ad hoc sibling test entrypoints.
- Do not keep compatibility shims, fallback implementations, or transitional APIs.
- Do not add aliases or targeted handling for removed configuration keys solely to support deprecated solver files.
- Delete dead code rather than hiding it behind
_unusednames or "removed" comments. - When a design changes, migrate call sites to the new design instead of preserving the old path.
- Do not mention external solver frameworks in code comments, examples, or commits. SolverForge is an independent implementation.
- Version bumps require explicit user confirmation.
CHANGELOG.mdstays undercsemver(configured incsemver.toml); do not hand-edit routine release notes unless the user explicitly asks for it.- GitHub Release bodies are generated by the release workflow from GitHub release notes; contributor credit on the release page comes from the
@mentionsin those generated notes.
-
make deps(inmake lint,make pre-releaseand the CI Docs job) fails on an unused direct dependency (cargo machete) and on a yanked or RustSec-flagged version inCargo.lock(cargo deny check advisories, configured indeny.toml). Remove a dependency in the same change that removes its last use. -
make build -
make examples -
make test -
make pre-release
make examples derives the package list from checked-in examples/*/Cargo.toml
manifests, so every workspace example should be covered without a manually
maintained package loop.
Minimum supported Rust version: 1.95+
Autonomous agent sessions in this repo load the in-repo drift-guard KV at session open:
nisaba --quiet docs/agents/drift-guard.nisaba scan drift-guard/Every record under the drift-guard/ prefix binds for the session. It
carries the plan-execution discipline: STATE.md verdicts are established
and never re-run, every tool call maps to an item in the task-packet
ledger, and the execution tripwire lists known recurring failure shapes.
Update the KV with nisaba inscribe ... --supersedes <id> and commit it
with the plan work that motivated the change.