Skip to content

Latest commit

 

History

History
462 lines (383 loc) · 25.4 KB

AGENTS.md

File metadata and controls

462 lines (383 loc) · 25.4 KB

AGENTS.md

Engineering guidance for all contributors, including autonomous coding agents.

Contribution Policy

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.

Overview

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.

Documentation Layer

Treat the repository documentation as a coordinated surface, not as isolated files.

  • README.md is 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 with solverforge-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 the assets/solverforge-architecture.svg diagram, 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; use CHANGELOG.md for release history and RELEASE.md for maintainer release operations.
  • The user guides docs/modeling.md, docs/constraints.md, docs/configuration.md, docs/running-solves.md and docs/performance.md hold 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.rs lists 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.md is each published crate's crates.io page: one paragraph on what the crate is, pointing applications at the solverforge facade. The facade's page is the root README.md. Every published crate also packages LICENSE (a symlink to the root file), and make publish-crates-dry fails on a manifest has no packaging warning.
  • CONTRIBUTING.md owns 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.md files are the canonical public API maps. Update them for any public surface change.
  • The other docs/*.md files (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 under docs/; current public APIs belong in the user guides and matching wireframes, while durable repository rules belong here.
  • docs/architecture.html is the generated system wiring map (crates, configuration, solve pipeline, runtime anatomy, consumers). Edit its vector source at assets/solverforge-architecture.svg and page layout at scripts/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.md records 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 __internal bridges. Do not document a module-only or macro-only symbol as if it were a supported root-level facade export.

Wireframes Are Canonical

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.md
  • crates/solverforge-bridge/WIREFRAME.md
  • crates/solverforge-core/WIREFRAME.md
  • crates/solverforge-macros/WIREFRAME.md
  • crates/solverforge-scoring/WIREFRAME.md
  • crates/solverforge-solver/WIREFRAME.md
  • crates/solverforge-config/WIREFRAME.md
  • crates/solverforge-console/WIREFRAME.md
  • crates/solverforge-cvrp/WIREFRAME.md

When public surface changes, update the matching wireframe in the same change:

  1. Add new public types, traits, functions, and modules.
  2. Update renamed items and changed signatures.
  3. Remove deleted public items completely.
  4. Keep file maps in sync with added or moved files.
  5. 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.toml workspace version and the exact (=x.y.z) inter-crate dependency versions in every crate manifest, which csemver's postbump moves together
  • README.md (status line and install snippet)
  • docs/running-solves.md (console banner)
  • AGENTS.md
  • affected crates/*/WIREFRAME.md files

Architecture Constraints

Zero-Erasure

All hot-path code must stay monomorphized.

  • Do not introduce Box<dyn Trait> in hot paths.
  • Do not introduce Arc<T> or Rc<T>.
  • Do not introduce dyn Trait unless it is an existing intentional boundary.
  • Avoid .clone() in move evaluation and scoring paths. Scoring streams do not require Clone on entity types, so generic scoring code cannot clone an entity; do not add a Clone bound to make one compile. Constraint analysis describes an entity by its type name, Debug rendering 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":

  • EntityExtractor in solverforge-core: runtime-erased SolutionDescriptor access only. Canonical generated RuntimeModel and scoring-stream paths retain concrete collection types.
  • DynamicScalarAccess, DynamicListAccess, DynamicListMetadata, and DynamicScalarAssignmentMetadata: host-language dynamic-model slot boundaries only.
  • RuntimeCandidateMetric: explicit configured host metric boundary for Sorted and Probabilistic selector ordering only.
  • RuntimeHostCompoundProvider in builder/context/provider: host-language callbacks only. Static Rust candidate and repair providers must stay on their concrete function-pointer and typed-ScalarEdit path.
  • RuntimeHostProviderErrorBoundary in builder/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-job Box<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.

Move Ownership

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:

  1. Solution snapshots sent through channels.
  2. 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.
  3. Explicit user-owned result snapshots outside retained scoring state, such as CollectedVec::to_vec() when the caller deliberately asks for an owned Vec<T>.

Collector Ownership

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 Node Sharing

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/reward so 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.

Joined Filter Indexes

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/PentaFilter indexes 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.

Neighborhood Hot Paths

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 (SelectorCompositionBorrowedCursor over RuntimeNeighborhoodState, which RuntimeNeighborhoodFlatCursor and RuntimeNeighborhoodLeafCursor schedule), 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 shared list_kernel emitters.
  • 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 keep open_cursor() loops explicit when abstraction hurts throughput or clarity.
  • Do not accept a median throughput regression greater than 5% without explicit user approval.

List Owner Restrictions

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.

CVRP Route Hooks

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_feasible are strict route-local gates and must reject structurally invalid, over-capacity, and time-window-infeasible routes before route-local phases such as ListKOpt commit a reversal.
  • savings_hooks::feasible / savings_feasible are 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 explicit route_hooks / savings_hooks; do not add compatibility aliases around the profile defaults.

Threading

Use rayon for CPU-bound work and tokio for async coordination.

  • Prefer rayon::spawn, rayon::scope, and parallel iterators.
  • Use tokio::sync::mpsc for 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::join plus 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 Completion

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.

PhantomData

For phantom type parameters, prefer PhantomData<fn() -> T> rather than PhantomData<T> so the phantom does not inherit unnecessary Send, Sync, or Clone bounds.

Manual Clone

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.

Code Organization

  • Keep every mod.rs and lib.rs limited to module declarations and use re-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 in solverforge-macros/src/lib.rs are 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-bridge and solverforge-cvrp) warns on missing_docs through 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 (in make lint, make pre-release and the CI Docs job) fails on any *.rs file under crates/ or examples/ longer than 500 lines.
  • The solverforge facade is the single dependency: every type a facade item's signature uses must be importable from solverforge (a root re-export or one of its layer modules). make facade-reachability (in make lint, make pre-release and 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.rs siblings 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.

Change Policy

  • 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 _unused names 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.md stays under csemver (configured in csemver.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 @mentions in those generated notes.

Build And Validation

  • make deps (in make lint, make pre-release and the CI Docs job) fails on an unused direct dependency (cargo machete) and on a yanked or RustSec-flagged version in Cargo.lock (cargo deny check advisories, configured in deny.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+

Agent Session Discipline

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.