Worked examples

65 real problems, already solved and verified.

Every example below is a complete, runnable template: the JSON problem, the engine-verified expected answer, how to read the result, and the encoding recipe behind it. Copy one, swap in your data, run it. Each was solved on the real engine before it shipped — the expected values are measurements, not aspirations.

Get them live (always current) or read them here

The catalogue is served by the API itself, so examples added on the server appear without a reinstall — prefer the live routes when you are a program; this page mirrors the bundled set for reading and search. No authentication is needed for any of these.

SurfaceHow
GET https://api.hexstellar.com/api/v1/examples the full catalogue as JSON (add ?client=<version> to pre-filter by CLI capability)
GET https://api.hexstellar.com/api/v1/examples/{id} one complete example — metadata, runnable problem, engine-verified expected
hexstellar examples CLI list (live-first, bundled fallback); hexstellar example <id> for one, --full for everything
hexstellar.examples() Python API — same for hexstellar.example("<id>"); both return dicts
https://docs.hexstellar.com/examples/examples.md this whole catalogue as ONE plain-markdown file — the friendliest format for AI fetchers
https://docs.hexstellar.com/examples/index.json the raw catalogue index (id · title · category · command) as JSON
terminal
# run any example end-to-end in one line (no key needed — public sandbox):
hexstellar example finance_portfolio --format json | hexstellar solve optimize

# or over raw HTTP:
curl -s https://api.hexstellar.com/api/v1/examples/finance_portfolio

18 encoding shapes behind the 65 titles

This file indexes 65 worked examples; each entry names one command, and the matching per-example file holds a runnable problem with the stored answer it reproduces. A title is a label on a reusable encoding shape, not the boundary of what that example solves: every example declares a shape and an also_solves list of named problems from other industries that submit the identical structure under different names, so the 65 titles are 65 of the 488 named problems in this catalogue and a reader who stops at the titles discards the other 423. Read the top-level shapes object next — it groups the 65 titles into 18 encodings and names the example that best teaches each one — then open a per-example file, where every also_solves entry carries the field-by-field mapping that turns that problem into this example's input. Canonical recipes explicitly start at flash: record that baseline first, then request medium or high only when deeper search is worth the measured cost. Effort never upgrades a heuristic result into a certificate.

subset-with-pairwise-interaction

You give every candidate a standalone value and give each pair of candidates a value that applies only when both are taken; the answer is the subset with the best total.

3 examples · 24 named problems · template: Portfolio Selection
assignment-under-conflict

You give the items, the slots each item may take, and for each pair a cost or a prohibition that applies when they share a slot; the answer is one slot per item.

16 examples · 130 named problems · template: Register Allocation Colorer
cover-the-requirements

You give the requirements, the candidate items with the requirements each one covers, and what each item costs; the answer is the cheapest family of items that covers every requirement as many times as that requirement demands.

8 examples · 55 named problems · template: CI Test Suite Selection
satisfy-declared-rules

You give the decisions as yes/no variables and the rules over them — exactly one of these, exactly k of those, at most k, if this then that, the same as, different from, pinned on, pinned off — and the answer is an assignment plus the count of rules it breaks.

10 examples · 71 named problems · template: Multi-Agent Action Arbiter
choose-k-of-m

You give m candidates a score each and every pair a penalty for the overlap between them, and you state k; the answer is a shortlist whose size is exactly k.

4 examples · 32 named problems · template: Biomarker Panel Selection
partition-into-two

You give a weight to every pair of items that is worth keeping apart; the answer puts each item on one of two sides so that the total weight of the separated pairs is as large as it can be.

3 examples · 23 named problems · template: Fault-Domain Partitioning
sequence-over-costs

You give one square table holding the cost of going from each item to every other item; the answer is the order that takes every item once and returns to the start for the least total cost.

2 examples · 14 named problems · template: Last-Mile Delivery Route
mixed-integer-with-continuous

You declare some variables as yes/no and others as continuous quantities inside stated bounds, then give one objective over both in linear and pairwise terms; the answer sets every variable of both kinds.

2 examples · 14 named problems · template: Recycling Line Dispatch & Sizing
aggregate-noisy-orders

You give the items and the pairwise verdicts collected about them, contradictions included; the answer is one order over all of them that agrees with as many of those verdicts as possible.

1 example · 8 named problems · template: LLM Judge Consensus Ranking
spectral-readout

You give the symmetric matrix that describes the system; the answer is its eigenvalues, its ground-state energy and the gap above that energy.

1 example · 7 named problems · template: Spin Hamiltonian Spectrum
verified-scientific-operation

A structured scientific or numerical operation with an independently recomputable invariant; optimality does not apply unless a separate bound says it does.

6 examples · 18 named problems · template: Known Entropy Spectrum
parity-system

Binary variables linked by exclusive-or equations; the returned assignment is checked clause-by-clause over GF(2).

1 example · 3 named problems · template: GF(2) Consistency Check
binary-energy

Binary states with local and pair terms, optionally with fixed outputs; every returned energy is recomputable from the supplied coefficients.

2 examples · 6 named problems · template: Known Coupled Ground State
scientific-hypothesis

A controlled classifier or proxy whose output is explicitly a hypothesis and must be checked with an independent experiment or contrast.

1 example · 3 named problems · template: Controlled Phase Hypothesis
planted-scale-certificate

A seeded construction with a known planted floor used to test scale, precision and transport without generalizing to arbitrary hard instances.

1 example · 3 named problems · template: 65,536-Variable Planted Floor
empirical-distribution

Many draws and distribution diagnostics from a coupled binary model; the result is empirical evidence, not one proven optimum.

1 example · 3 named problems · template: Enumerable Distribution Sample
integrity-roundtrip

A typed protect/recover round-trip whose public assurance comes from byte equality and an independently reproduced digest.

2 examples · 6 named problems · template: Protected Payload Envelope
multi-layer-resolution

A bounded dependency graph of supported capabilities and typed external evidence whose public claims are guarded by explicit residual criteria.

1 example · 3 named problems · template: Residual-Guarded Fault Isolation

Catalogue — 65 examples in 27 categories

AI Infrastructure
Agriculture
Biotech
Cloud
Culture
DevOps
Education
Energy
Engineering
Finance
Gaming
Healthcare
Infrastructure
Legal
Logistics
Manufacturing
Music
Operations
Quantum & Physics
Real Estate
Robotics
Scheduling
Scientific Computing
Security
Space
Sustainability
Telecom

AI Infrastructure

🧩 Multi-Agent Action Arbiter

AI Infrastructure · command rules · effort flash · id: agent_action_arbiter

Exclusive use of a resource is capacity_limit k=1 over all claimants, not g(g-1)/2 pairs; the world's current state enters as force_true.

When many autonomous agents each propose an action, some proposals conflict: two want to write the same file, one wants to delete a database while a backup is running, a test can't run before a compile, and only one GPU slot is free. HexStellar returns the set of actions that may all execute at once without breaking a single rule — here with zero violations. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is 1 when proposed action i is cleared to execute. violations is 0 when every dependency, mutual-exclusion, and resource rule holds.

Where this shows up

Multi-agent orchestration, action admission control, write-conflict avoidance, GPU/API/rate-limit arbitration — the transaction manager that decides which proposed actions become reality.

The same encoding also solves 8

  • Approving a substation switching programUtilities
    proposed actions → requested breaker and isolator operations, requires [X,Y] → the interlock that X is permitted only once Y is in place, mutual_exclusion → two operations that together parallel two sources, capacity_limit k → the qualified switching crews available, force_true → the isolations already in place when the program starts; the answer states WHICH operations may be authorised together, not the order of the steps — step ordering is outside what this command expresses
  • Issuing hot-work permits for a refinery turnaroundProcess safety
    proposed actions → requested permits, requires → the rule that a hot-work permit is valid only once the line's isolation permit is issued, mutual_exclusion → hot work and tank venting in the same area, capacity_limit k → the fire-watch teams, force_true → the isolations and permits already in force
  • Releasing a cutoff batch of payment instructionsBanking operations
    proposed actions → instructions proposed for release, requires → an instruction that may go only once its funding leg is released, mutual_exclusion → two instructions the same collateral pool cannot fund together, capacity_limit k → the NUMBER of releases the clearing channel accepts at once, force_true → the instructions already committed; a liquidity cap measured in value is a weighted budget rather than a count — carry the amounts as a penalty in the optimize objective (the settlement-netting example is the worked version)
  • Clearing concurrent pad operations during a countdown holdSpace operations
    proposed actions → requested pad operations, requires → fuelling permitted only once the pad-clear state is declared, mutual_exclusion → hypergolic loading and crew ingress, capacity_limit k → the ground-support connections available, force_true → the operations already underway
  • Choosing which promotions may all run in one circularRetail
    proposed actions → proposed promotions, requires → a bundle promotion valid only with its anchor SKU promotion, mutual_exclusion → two promotions competing for the same endcap, capacity_limit k → the feature slots on a page, force_true → promotions already contracted with a vendor
  • Deciding which protocol amendments can be enacted at one trial siteClinical research
    proposed actions → proposed amendments, requires → an amendment enactable only once its ethics-committee approval is recorded, mutual_exclusion → two amendments editing the same dosing table, capacity_limit k → the amendments one submission accepts, force_true → the approvals already granted
  • Admitting add-on surgical cases to a theatre listHealthcare
    proposed actions → add-on cases requesting a theatre, requires → a case that may proceed only once its pre-operative clearance is recorded, mutual_exclusion → two cases needing the same mobile imaging unit, capacity_limit k → the anaesthetists on duty, force_true → the cases already under way; this admits a set of cases that may run in the same session — it does not order them or fit their durations, and case minutes are a weighted budget for optimize
  • Authorising concurrent underground activities on a mine panel planMining
    proposed actions → requested underground activities, requires → blasting permitted only once the panel-evacuation state is declared, mutual_exclusion → blasting in one panel and drilling in the panel sharing its ventilation split, capacity_limit k → the panels the ventilation circuit can serve at once, force_true → the activities already authorised

Measured at scale actually run

The same admission encoding has been measured on 100,000 proposed-action variables under 30,000 declared dependency, exclusion and resource rules submitted as one 1,602 KB request; the set cleared to execute carries a rule-violation count that is certified minimal and independently checked.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape at 20,000 proposed operations is 20,000 binary variables, one requires per dependency edge and one mutual_exclusion per conflicting pair, so 12,000 dependencies plus 30,000 conflicting pairs is 42,000 rules in one request, with one force_true per fact already true. A resource touched by g proposals costs g(g-1)/2 pairwise exclusions or a single capacity_limit with k=1 over all g nodes, so the same exclusivity is stated in one rule instead of thousands, and violations is reported per answer, where zero certifies that every declared rule holds.

The encoding recipe (agent notes)

THIS IS AGENT ORCHESTRATION AS A CONSTRAINT PROBLEM — and it is probably YOU. Each proposed action is a boolean. 'Run-tests needs a compile first' → requires [run_tests, compile]. 'Never delete the DB while a backup runs' → mutual_exclusion [delete_db, backup_running]. 'Two agents can't both write the same file' → mutual_exclusion on the two writes. 'Only k GPU slots' → capacity_limit. State that is already true (a backup IS running) → force_true, which then blocks whatever conflicts with it. COMMON MISTAKES: (1) requires direction — [run_tests, compile] means run_tests⇒compile, not the reverse; (2) forgetting to force_true the world's current state (the running backup), so the arbiter doesn't know to block the delete; (3) wanting a WEIGHTED trade-off ('this conflict costs 27, that reward is worth 10, maximize net value') — hard rules only says yes/no; move weighted/soft conflicts to optimize (a positive quadratic penalty per conflicting pair, a negative linear reward per desired action). THE BIG IDEA: LLMs are proposal generators; this is the serializability layer that decides which proposals may coexist. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Decide which proposed agent actions may all execute together this tick.",
 "n": 8,
 "constraints": [
  {
   "type": "requires",
   "nodes": [
    0,
    1
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    2,
    3
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    4,
    5
   ]
  },
  {
   "type": "capacity_limit",
   "k": 1,
   "nodes": [
    6,
    7
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    0
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    3
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example agent_action_arbiter --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/agent_action_arbiter        # the full example over HTTP

🗳️ LLM Judge Consensus Ranking

AI Infrastructure · command rank · effort flash · id: ai_judge_consensus

No scores, only [winner, loser] pairs — repeat a pair to weight it; cycles are legal input, and the answer's unit is verdicts contradicted.

Three reviewer agents compared four candidate drafts head-to-head, and their verdicts conflict: most say draft A beats B, but one judge said B beats A; one said D beats A; one said C beats B. Majority-voting each pair separately can even produce a cycle with no winner. HexStellar returns the Kemeny consensus — the full ordering that contradicts the fewest individual verdicts. Here: A, B, C, D, disagreeing with exactly 4 of the 16 recorded comparisons, which brute-force enumeration of all 24 orderings confirms is the unique optimum. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is the items best-first — the consensus ranking. disagreements counts how many input comparisons the consensus order contradicts; it is the minimized objective and the field to test.

Where this shows up

LLM-as-judge panels, A/B test arbitration, meta-search result merging, peer-review aggregation, tournament seeding, preference-data cleanup for RLHF — anywhere several imperfect rankers must become one defensible order. The same math (minimum feedback arc set) also RECONSTRUCTS an order from noisy precedence observations: process-flowsheet step ordering from 'A must precede B' reports, archaeological layer chronology from conflicting 'stratum A underlies B' field notes, treatment-line prioritization from head-to-head trial outcomes, dependency untangling in legacy build systems. Multi-physics coupling-stage ordering (fluid, structure, thermal) from noisy 'A before B for numerical stability' evidence is the same reconstruction.

The same encoding also solves 8

  • Build one product order from a sensory panel where 20 tasters gave paired-preference verdicts that contradict each otherConsumer goods
    items → product formulations on test, each [winner, loser] → one taster's paired-preference verdict, a repeated pair → the number of tasters preferring that formulation in that pair, disagreements → taster verdicts the published order contradicts
  • Order champion and challenger credit scorecards from head-to-head A/B outcomes across segments that disagreeFinancial services
    items → scorecard versions, each [winner, loser] → one segment's A/B outcome naming the better scorecard, a repeated pair → how many segments reported that same outcome, disagreements → segment outcomes the final ranking contradicts; a fractional confidence weight has no term here, so round it to a repeat count first
  • Seed a 128-player bracket from a season of head-to-head results containing upsets and no common opponentsEsports
    items → players, each [winner, loser] → one completed match, a repeated pair → how many times that player beat the other, disagreements → match results the seeding order contradicts; a draw is not expressible, so drop it or record one verdict each way
  • Rank 30 process recipes from split-lot wafer comparisons where different metrology tools named different winnersSemiconductor
    items → process recipes, each [winner, loser] → one split-lot comparison naming the better recipe, a repeated pair → the number of lots or tools calling it that way, disagreements → split-lot comparisons the final recipe order contradicts
  • Turn ranked-choice ballots into one committee-wide order when no candidate beats every other candidate pairwiseElections / civic
    items → candidates, each [winner, loser] → one ordered pair extracted from a single ballot's ranking, a repeated pair → the number of ballots placing that candidate ahead, disagreements → ballot pairs the declared order contradicts
  • Order 40 catalyst candidates from paired bench runs where duplicate runs reversed the verdictChemicals
    items → catalyst candidates, each [winner, loser] → one paired bench run naming the higher-yielding catalyst, a repeated pair → the number of runs that agreed, disagreements → bench runs the published order contradicts
  • Order 25 triage protocols from clinicians' paired preference judgments recorded across shifts that disagreeHealthcare operations
    items → triage protocols, each [winner, loser] → one clinician's paired judgment, a repeated pair → the number of clinicians judging it that way, disagreements → clinician judgments the adopted order contradicts
  • Rank grasp policies from teleoperator preference votes where operators disagree about which policy emptied a bin betterRobotics
    items → grasp policies, each [winner, loser] → one operator's preference on a paired trial, a repeated pair → how many operators or trials preferred that policy, disagreements → operator votes the final policy order contradicts

Measured at scale actually run

The same two fields carry 2,000 judged drafts and 119,949 recorded [winner, loser] verdicts — roughly 22% of them contradicted by another verdict — as a single 3,305 KB request, and one consensus order is returned for the whole set. That order is labelled heuristic, meaning it is a hypothesis rather than a proven optimum: recount its disagreements against the raw comparison list with the free verify call before you publish the ranking.

Instance
2,000 items · 119,941 comparisons · ~22% contradictory
Answer
heuristic (labelled)
Engine time
135 ms (135 ms–135 ms, n=3)
Peak memory
40.5 MB
Request
3,305 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rank --sizes target

How the encoding grows

The identical encoding at 400 items judged by 12 panels is 400 item labels and 957,600 comparison entries — each panel's full set of 79,800 ordered pairs — in one request with the same two fields, items and comparisons. The ordering count is 400 factorial, so above the small certified range the answer carries the heuristic label rather than a proof, and disagreements stays an integer you recount against the raw comparison list yourself.

The encoding recipe (agent notes)

THE ENCODING RECIPE: rank takes items and a flat list of comparisons, each [winner, loser]. Repeat a pair to weight it — three judges saying A beats B is three entries. Contradictions are EXPECTED input, not errors: minimizing total disagreements across them is the whole (NP-hard, Kemeny) problem. COMMON MISTAKES: (1) majority-voting each pair independently — pairwise majorities can form a CYCLE (A beats B beats C beats A, the Condorcet paradox) and then no consistent order exists locally; the consensus ORDER is exactly what this command restores; (2) asserting the returned order in tests — other instances can have tied optima, so the invariant to store is disagreements (here the optimum happens to be unique, proven by enumerating all 24 orders); (3) feeding scores — if every item already has a clean numeric score, just sort; rank earns its keep when judges only produced RELATIVE verdicts and those verdicts conflict; (4) the output is a hypothesis to verify — recount the disagreements of the returned order against the raw comparisons; the count must match the reported field. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Merge many judges' noisy pairwise verdicts into the single order that disagrees with them least.",
 "items": [
  "draft_a",
  "draft_b",
  "draft_c",
  "draft_d"
 ],
 "comparisons": [
  [
   "draft_a",
   "draft_b"
  ],
  [
   "draft_a",
   "draft_b"
  ],
  [
   "draft_b",
   "draft_a"
  ],
  [
   "draft_a",
   "draft_c"
  ],
  [
   "draft_a",
   "draft_c"
  ],
  [
   "draft_a",
   "draft_d"
  ],
  [
   "draft_a",
   "draft_d"
  ],
  [
   "draft_d",
   "draft_a"
  ],
  [
   "draft_b",
   "draft_c"
  ],
  [
   "draft_b",
   "draft_c"
  ],
  [
   "draft_c",
   "draft_b"
  ],
  [
   "draft_b",
   "draft_d"
  ],
  [
   "draft_b",
   "draft_d"
  ],
  [
   "draft_c",
   "draft_d"
  ],
  [
   "draft_c",
   "draft_d"
  ],
  [
   "draft_d",
   "draft_c"
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "answer": [
  "draft_a",
  "draft_b",
  "draft_c",
  "draft_d"
 ],
 "disagreements": 4
}

Run it

terminal
hexstellar example ai_judge_consensus --format json | hexstellar solve rank
curl -s https://api.hexstellar.com/api/v1/examples/ai_judge_consensus        # the full example over HTTP

🧠 Tensor / GPU Shard Placement

AI Infrastructure · command qap · effort flash · id: ai_tensor_placement

Two same-size matrices over different sets: flow over the items, distance over the places. Spare places enter as zero-flow padding items.

Training a large model splits it into shards that exchange gradients and activations every step. Some shard pairs are far chattier than others, and some GPU ranks are connected by a fast link (NVLink) while others only talk over slower fabric. HexStellar assigns each shard to a rank so the total traffic × link-latency is minimized — pulling the heaviest-communicating shards onto the lowest-latency rank pairs. For this size the placement is a certified optimum. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is a permutation: answer[i] is the GPU rank assigned to shard i. cost is total traffic×latency (lower means less communication stall).

Where this shows up

Tensor/pipeline/context-parallel layout, GPU cluster sharding, NUMA/core pinning, NIC-affinity placement, logical-qubit-to-physical-topology mapping (circuit interaction counts as flow, hardware coupling distances as dist) — any 'put the heavily-talking parts on the fastest link' problem.

The same encoding also solves 11

  • Initial logical-to-physical qubit mapping on a fixed coupling graphQuantum computing
    flow → number of two-qubit gates between logical qubits i and j in the circuit, dist → shortest-path length between physical qubits a and b in the coupling graph (the routing cost of one interaction), answer[i] → the physical qubit holding logical qubit i; flow and dist must be the same size, so when the device has more physical qubits than the circuit has logical ones, pad flow with zero-gate placeholder logical qubits up to N — a placeholder contributes nothing to cost and the physical qubits it lands on are the ones left empty; this fixes the static starting map only, per-layer rerouting is a separate decision the encoding does not carry
  • Recovering a monoalphabetic substitution key from digram statisticsCryptanalysis
    flow → observed count of the ciphertext symbol pair (i,j), dist → (highest reference frequency − expected frequency of the plaintext letter pair (a,b) in the language table), with the reference table scaled to whole numbers (frequencies per million, not fractions — flow and dist carry integer entries), so minimizing the products maximizes agreement between the two digram tables, answer[i] → the plaintext letter assigned to ciphertext symbol i
  • Aligning two protein-interaction networks across speciesComputational biology
    flow → interaction confidence between proteins i and j in species A, dist → (max confidence − interaction confidence between proteins a and b in species B), both confidence tables scaled to whole numbers (e.g. confidence x 1000, since flow and dist carry integer entries), so the minimum is the alignment that conserves the most interaction weight, answer[i] → the species-B protein matched to species-A protein i; unequal network sizes are padded with zero-interaction placeholders, which contribute nothing to cost
  • Thermal-aware server placement inside a rackData-center facilities
    flow → the product of the sustained power draws of servers i and j (so a hotspot costs most when two heavy servers sit in coupled positions — a pair SUM would collapse the objective into a per-position linear cost), dist → thermal coupling between rack positions a and b (large for positions sharing an airflow path), answer[i] → the rack position for server i, cost → total heat-coupling exposure; a position's own cooling penalty is a per-location linear cost qap has no field for, so when it dominates, restate the instance as rules: one binary per (server, position), choose_one per server and per position, linear = draw x that position's cooling penalty, quadratic = the same draw-product x coupling terms
  • Assigning avionics line-replaceable units to equipment-bay slots to shorten the wiring harnessAerospace systems
    flow → the number of conductors running between LRU i and LRU j on the wiring schematic (whole-number wire count per pair; unconnected units contribute 0), dist → routed cable length in centimetres between bay slot a and bay slot b measured along the airframe's permitted raceways rather than straight-line, answer[i] → the bay slot that receives LRU i, cost → total conductor-centimetres, the quantity harness mass and voltage drop both track; flow and dist must be the same N, so when the airframe offers more slots than there are units, pad flow with zero-conductor placeholder units — a placeholder adds nothing to cost and the slots it lands on are the ones left empty. A slot's own admissibility (this unit may not sit in an unpressurised or unheated bay) is a per-slot rule qap has no field for: restate the instance as rules — one binary per (unit, slot), choose_one per unit and per slot, force_false on every inadmissible (unit, slot) pair, quadratic = the same wire-count x run-length products.
  • Arranging camera feeds on a live gallery's monitor wall so the director's eyes travel lessBroadcast production
    flow → the number of times feed i and feed j were cut back-to-back in the logged rundowns of past editions of the show (a symmetric whole-number count per pair), dist → eye-travel distance in whole centimetres between monitor position a and monitor position b on the wall, answer[i] → the monitor position given to feed i, cost → total cut-weighted eye travel across the logged rundown, minimized so the pairs the director switches between most sit closest together; both matrices are N x N over the same N, so a monitor kept spare is a zero-cut placeholder feed and the position it takes is the one left dark. Fixed positions (programme and preview stay dead centre) are pins qap has no field for: express them with rules — one binary per (feed, position), choose_one per feed and per position, force_true on the pinned (feed, position) binaries, quadratic = the same cut-count x eye-distance products.
  • Placing process units on a refinery plot plan to cut total pipe runProcess engineering
    flow → design mass throughput between unit i and unit j in whole tonnes per hour, summed over every line connecting them (a heavier duty costs more per metre of pipe and more pumping), dist → routed pipe-rack length in metres between plot area a and plot area b, answer[i] → the plot area assigned to unit i, cost → total tonne-per-hour-metres, the quantity piping capital cost tracks; both matrices are N x N over the same N, so plot areas held for a future train enter flow as zero-throughput placeholder units. Minimum separation between hazardous neighbours (the fired heater may not sit beside the tank farm) is a forbidden pairing qap has no field for: state it with rules — one binary per (unit, area), choose_one per unit and per area, one mutual_exclusion rule per forbidden combination whose nodes are the (heater, area a) and (tank, area b) binaries for each adjacent a,b, quadratic = the same throughput x pipe-length products.
  • Zoning a supermarket floor so categories bought together sit within a short walkRetail store planning
    flow → the number of till baskets in the last quarter that contained an item from category i and an item from category j (a whole-number co-purchase count read straight off the transaction log), dist → walking distance in metres between floor zone a and floor zone b along the aisles as a shopper actually walks them, answer[i] → the floor zone that receives category i, cost → total shopper-metres walked over the measured baskets, minimized; both matrices are N x N over the same N, so a zone reserved for a seasonal display enters flow as a zero-basket placeholder category. Per-zone eligibility (chilled goods only land on a zone with refrigeration, bulk goods only on a zone the pallet truck can reach) is a per-location rule qap has no field for: carry it in rules — one binary per (category, zone), choose_one per category and per zone, force_false on every ineligible pair, quadratic = the same co-purchase x walking-distance products.
  • Seating orchestra sections on the risers of an unfamiliar hallLive performance
    flow → how tightly two sections must lock together, counted from the score as the number of bars in the programme where section i and section j carry the same rhythmic figure (a whole number per pair; sections that never coincide contribute 0), dist → acoustic propagation delay in whole milliseconds between riser position a and riser position b as measured in the hall during the sound check, answer[i] → the riser position given to section i, cost → total bar-milliseconds of ensemble lag, minimized so the pairs that must play together get the shortest acoustic path; both matrices are N x N over the same N, so an unused riser is a zero-bar placeholder section. Physical fit (the harps need a riser deep enough, percussion needs the back wall) is a per-position feasibility rule qap has no field for: restate with rules — one binary per (section, riser), choose_one per section and per riser, force_false on risers that cannot hold the section, quadratic = the same bars x delay products.
  • Assigning species to the enclosures of a new zoo precinct so stress-inducing neighbours are kept apartZoo husbandry
    flow → the recorded antagonism between species i and species j, as the count of stress behaviours logged per hundred observation hours when the two were previously within sight, earshot or scent of each other (a whole number per pair; species that ignore each other contribute 0), dist → exposure between enclosure a and enclosure b, scored 0-100 from the sightline and acoustic survey (high for two enclosures facing each other across one path, 0 for enclosures screened by planting and a service road) — this term is an EXPOSURE rather than a metric distance, which is exactly what makes minimizing the products push antagonistic pairs onto mutually screened enclosures, answer[i] → the enclosure that receives species i, cost → total stress exposure across the precinct; both matrices are N x N over the same N, so an enclosure held back for quarantine enters flow as a zero-antagonism placeholder species. An enclosure's own suitability (pool depth, heated house, browse height) is a per-enclosure requirement qap has no field for: carry it in rules — one binary per (species, enclosure), choose_one per species and per enclosure, force_false on unsuitable pairs, quadratic = the same antagonism x exposure products.
  • Ordering grave assemblages into a chronological sequence from shared artefact typesArchaeology
    flow → similarity between assemblage i and assemblage j, as the count of artefact types the two graves have in common (a whole number; graves sharing nothing contribute 0), dist → |a - b|, the number of steps apart sequence slots a and b are on the timeline, answer[i] → the sequence slot assigned to assemblage i, cost → total similarity x slot separation, whose minimum is the ordering that keeps the most alike assemblages closest in time — the seriation itself; the timeline is defined to have exactly one slot per assemblage, so both matrices are N x N with no padding needed, and an answer and its reversal carry the same cost because this encoding fixes the ordering, not its direction (which end is early comes from an external dated find). Anchoring a coin-dated grave to a known slot is a pin qap has no field for: express it with rules — one binary per (assemblage, slot), choose_one per assemblage and per slot, force_true on the dated (assemblage, slot) binary, quadratic = the same shared-type x slot-separation products.

Measured at scale actually run

Two 200x200 matrices - 200 model shards against 200 GPU ranks, 40,000 shard-traffic entries and 40,000 rank-latency entries - make one 294 KB request, and what comes back is a complete shard-to-rank permutation, labelled heuristic rather than certified, so re-cost it with the free verify call before treating it as the best placement.

Instance
200 variables · 40,000 flow entries · 40,000 distance entries
Answer
heuristic (labelled)
Engine time
26 ms (26 ms–26 ms, n=3)
Peak memory
3.0 MB
Request
294 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only qap --sizes target

How the encoding grows

The identical shape at 128 shards is two 128x128 matrices — 32,768 numbers in one request, 8,128 unordered pairs on each side — and the objective is a sum of 16,256 flow-by-distance products over one assignment out of 128! possible ones. Only the numbers grow; the request still carries exactly the two fields it carries at n=4, and the certainty label is reported per answer, so past the exhaustion cap the response is a labelled heuristic rather than a silent guess.

The encoding recipe (agent notes)

THIS IS THE SAME QAP ENGINE AS SERVICE-MESH AND CHIP-FLOORPLAN PLACEMENT — the story changes, the shape doesn't. flow[i][j] = communication volume between shard i and shard j (GB/step, all-reduce bytes, RPCs — whatever your traffic unit is); dist[a][b] = latency between rank a and rank b (NVLink ≈ small, cross-fabric ≈ large). Minimizing Σ flow·dist minimizes aggregate communication cost. COMMON MISTAKES: (1) swapping the matrices — flow is indexed by SHARDS, dist by RANKS; they're the same size but mean different things; (2) expecting an on/off vector — qap returns a one-to-one assignment (each rank holds one shard); (3) trying to also enforce a VRAM budget here — pure qap only minimizes communication. If you must ALSO cap per-rank memory or force a colocation ('these two shards must share an NVLink domain'), model it with rules (capacity_limit for VRAM, identical/mutual_exclusion for colocation) or combine the two. WHY IT LANDS: the optimum here places the two chattiest shard-pairs onto the two NVLink-connected rank-pairs — exactly what a human infra engineer hand-tunes, found by search. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Place model shards on GPU ranks so the chattiest pairs share the fastest link.",
 "flow": [
  [
   0,
   800,
   120,
   40
  ],
  [
   800,
   0,
   300,
   60
  ],
  [
   120,
   300,
   0,
   500
  ],
  [
   40,
   60,
   500,
   0
  ]
 ],
 "dist": [
  [
   0,
   10,
   90,
   60
  ],
  [
   10,
   0,
   60,
   45
  ],
  [
   90,
   60,
   0,
   12
  ],
  [
   60,
   45,
   12,
   0
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "cost": 83800,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example ai_tensor_placement --format json | hexstellar solve qap
curl -s https://api.hexstellar.com/api/v1/examples/ai_tensor_placement        # the full example over HTTP

🖥️ GPU Fleet Scheduling With Tenant Isolation

AI Infrastructure · command rules · effort flash · id: cloud_gpu_scheduler

capacity_limit counts requests, not gigabytes: equal slots are native, weighted budgets are not; isolation is one exclusion per node.

An inference platform must place each incoming request on a GPU node. Every node holds only so many concurrent requests (its VRAM budget), and two competing tenants must never land on the same node. HexStellar assigns every request to a node so no node is over-subscribed and no isolation rule is broken — here five requests across two nodes with zero violations. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is one-hot per request: variable (request*2 + node) is 1 for the chosen node. violations is 0 when the per-node capacity and the tenant-isolation rules all hold.

Where this shows up

LLM inference scheduling, GPU/accelerator fleet packing, multi-tenant isolation, batch placement — the global version of a greedy 'find a free GPU' scheduler.

The same encoding also solves 7

  • Building commercial breaks under category-exclusivity clausesAdvertising
    requests → ad creatives to be scheduled, nodes → commercial breaks, choose_one → each creative airs in exactly one break, capacity_limit k → the equal-length spot slots in a break (spot lengths that differ are a weighted budget rather than a count — carry them as a penalty in the optimize objective), mutual_exclusion per break → the category-exclusivity clause barring two rival brands from one break; the price of each placement rides this command's optional linear objective
  • Seating a banquet against a do-not-seat listEvents
    requests → guests, nodes → tables, choose_one → each guest is seated at exactly one table, capacity_limit k → the covers per table (choose_exactly with k when a table must be filled exactly), mutual_exclusion per table → a pair on the do-not-seat list
  • Allocating detainees to housing blocks under keep-separate ordersCorrections
    requests → detainees awaiting placement, nodes → housing blocks, choose_one → each person is housed in exactly one block, capacity_limit k → the block's bed count, mutual_exclusion per block → a court-ordered keep-separate pair such as two co-defendants
  • Drawing a tournament group stage under association-protection rulesSport
    requests → qualified teams, nodes → groups, choose_one → each team lands in exactly one group, capacity_limit k → the group size cap, replaced by choose_exactly with k when every group must hold exactly k, mutual_exclusion per group → the protection rule barring two clubs from one association appearing in the same group
  • Assigning production lots to cleanroom tools under customer segregationSemiconductor manufacturing
    requests → production lots, nodes → process tools, choose_one → each lot runs on exactly one tool, capacity_limit k → the lots a tool holds concurrently, counted as equal slots (run lengths that differ are a weighted budget rather than a count — carry them as a penalty in the optimize objective), mutual_exclusion per tool → two customers' lots barred from one tool by an IP-segregation agreement
  • Routing claims to adjuster pools without putting both sides of one accident togetherInsurance
    requests → open claims, nodes → adjuster pools, choose_one → each claim is routed to exactly one pool, capacity_limit k → the pool's open-claim ceiling, mutual_exclusion per pool → the two claims arising from opposite sides of one accident, which must not be adjusted by one pool
  • Housing animals in enclosures with recorded aggression pairs kept apartAnimal management
    requests → animals to be housed, nodes → enclosures, choose_one → each animal is housed in exactly one enclosure, capacity_limit k → the enclosure's head-count limit, mutual_exclusion per enclosure → a pair with a recorded aggression incident

Measured at scale actually run

Measured at 100,000 request-on-node variables under 30,000 declared capacity and tenant-isolation rules, the same encoding returned a whole-fleet schedule from a 1,602 KB request within 16,588 KB of memory, its rule-violation count certified minimal and independently checked.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape at 2,000 requests across 40 resources is 2,000x40 = 80,000 binary variables, 2,000 choose_one groups, 40 capacity_limit rules, and one mutual_exclusion per resource per separated pair, so 10 separated pairs add 400 exclusions for 2,440 rules in one request. Requests x resources must stay within the declared ceiling of 100,000 variables, which a single request has carried in full, so a fleet past that ceiling is encoded one resource group at a time, and violations is reported per answer, where a positive count is the plain statement that the capacities and separations asked for were over-subscribed.

The encoding recipe (agent notes)

SAME RULES ENGINE, AI-INFRA STORY: 'this request runs on exactly one node' → choose_one over its per-node variables. 'a node holds at most k concurrent requests' → capacity_limit (a COUNT of requests). 'tenant A and tenant B must never co-locate' → mutual_exclusion per node on their same-node variables. COMMON MISTAKES: (1) treating VRAM as a weighted budget — capacity_limit counts REQUESTS (slots), not gigabytes; if requests have very different VRAM footprints, model the weighted budget with optimize instead; (2) forgetting choose_one, which lets a request run on zero or several nodes; (3) reading a non-zero violations as an error — it's the engine telling you the constraints are over-subscribed (too many requests for the nodes/isolation you demanded), which is your signal to add capacity or nodes. WHY IT MATTERS: a greedy scheduler places requests one at a time and drifts into a patchwork; this places them all at once so every isolation and capacity rule holds simultaneously. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Place inference requests on GPU nodes, respect VRAM slots, keep rival tenants apart.",
 "n": 10,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    2,
    3
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    4,
    5
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    6,
    7
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    8,
    9
   ]
  },
  {
   "type": "capacity_limit",
   "k": 3,
   "nodes": [
    0,
    2,
    4,
    6,
    8
   ]
  },
  {
   "type": "capacity_limit",
   "k": 3,
   "nodes": [
    1,
    3,
    5,
    7,
    9
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    2
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    1,
    3
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example cloud_gpu_scheduler --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/cloud_gpu_scheduler        # the full example over HTTP

🪟 RAG Context-Window Packing

AI Infrastructure · command select · effort flash · id: rag_context_packing

Reward is per item, penalty is per pair, so a near-duplicate keeps only what it adds beyond its twin — which is exactly where top-k fails.

A retriever returns many candidate chunks, but only a few fit in the context window. Picking the top-k by relevance packs in near-duplicates and wastes the budget. HexStellar picks the set that maximizes total relevance minus redundancy — the diverse, high-coverage context — here choosing three chunks that skip a near-duplicate pair entirely. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is the chosen chunk indices; value is total relevance minus pairwise redundancy; count is how many were selected (the budget k).

Where this shows up

RAG context assembly, prompt/token-budget packing, few-shot example selection, feature/sensor selection — any 'pick k of many to maximize coverage without paying for overlap'.

The same encoding also solves 8

  • Choose the 12 reinsurance treaty layers to bind for next season from 300 quoted layers, where layers covering the same peril region relieve the same exposureInsurance
    candidates → quoted treaty layers, k → layers the ceded programme binds, affinity → expected loss relieved by that layer, redundancy → peril-region exposure the other layer in the pair already relieves; a spend cap in currency is not a term here, so model unequal premiums as a weighted knapsack in optimize instead of using k
  • Pick the 6 creatives to run in one flight from 80 approved assets when creatives sharing a hook fatigue the same audienceAdvertising
    candidates → approved creative assets, k → slots in the flight, affinity → predicted lift per impression for that creative, redundancy → audience-overlap fatigue between a pair sharing a hook or a targeting segment
  • Select the 25 documents for a deposition exhibit binder from 4,000 responsive hits, where near-duplicate email threads consume binder slotsLegal / eDiscovery
    candidates → responsive documents, k → exhibit slots the binder holds, affinity → probative weight scored by the review team, redundancy → near-duplicate and thread-overlap score between a document pair
  • Choose the 40 detection rules to enable on a SIEM tier from 600 authored rules when several rules alert on the same attack techniqueCybersecurity
    candidates → authored detection rules, k → rules the tier's alert budget supports, affinity → historical true-positive value of the rule, redundancy → attack-technique coverage shared by a rule pair, which would double-alert one event
  • Choose 8 of 90 inline inspection stations to keep on a line where two stations catch the same defect classManufacturing QA
    candidates → candidate inspection stations, k → stations the takt permits, affinity → defect escapes prevented by that station, redundancy → defect classes both stations in the pair already catch
  • Select 15 of 400 cell sites for a fibre-backhaul upgrade round where adjacent sites carry the same trafficTelecom
    candidates → cell sites, k → upgrades funded this round, affinity → congested traffic relieved at that site, redundancy → subscriber traffic both sites in the pair already carry
  • Pick the 20 telemetry channels to downlink at full rate from 350 instrumented channels when several channels are derived from one sensorAerospace
    candidates → instrumented telemetry channels, k → channels the downlink allocation holds at full rate, affinity → diagnostic value of the channel in anomaly review, redundancy → shared source-sensor derivation between a channel pair
  • Choose the 10 stories for a newsletter front section from 250 filed pieces where two pieces on the same event competeMedia / Publishing
    candidates → filed stories, k → front-section slots, affinity → predicted read-through for that story, redundancy → topical overlap between a story pair covering one event

Measured at scale actually run

The same four fields over a 2,000-chunk retrieval pool picking 80 for the window, with 20,000 non-zero overlap pairs inside an 11,729 KB request, came back with all 80 slots filled and labelled heuristic (hypothesis — verify), so re-cost relevance-minus-redundancy with the free verify call before you treat it as the best packing.

Instance
2,000 candidates · 80 k · 20,000 overlap pairs
Answer
heuristic (labelled)
Engine time
5 ms (4 ms–5 ms, n=3)
Peak memory
5.8 MB
Request
11,729 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only select --sizes target

How the encoding grows

The identical encoding at 1,200 retrieved chunks with a 30-chunk budget is 1,200 affinity values plus a symmetric overlap matrix of up to 719,400 distinct pairs (1,440,000 matrix entries), submitted as one request with the same four fields: m, k, affinity, redundancy. Only the numbers grow, not the structure. Certification is proven by exhaustion and is labelled on every answer, so an instance this size returns a stated heuristic while the returned set still holds exactly 30 chunks.

The encoding recipe (agent notes)

TOP-K BY RELEVANCE IS THE WRONG ANSWER, AND THIS EXAMPLE SHOWS WHY. Give select the budget k, an affinity per chunk (its relevance to the query), and a redundancy matrix (pairwise semantic overlap). It maximizes Σ affinity(picked) − Σ redundancy(picked pairs) — so two chunks that say the same thing can't both earn their slot, and the winner is a DIVERSE, high-coverage set. COMMON MISTAKES: (1) leaving redundancy at zero — then you get plain top-k and pack in duplicates; the redundancy matrix is the whole point; (2) sign confusion — affinity is reward (higher = more relevant), redundancy is penalty (higher = more overlap); (3) treating k as 'a number of tokens' — it's a COUNT of chunks; if chunks have very different token sizes, model the token budget with optimize (a weighted knapsack) instead. THE ECONOMICS: every RAG and agent request pays this selection; better relevance-per-token is a direct quality and margin win at volume. Same shape selects biomarker panels, few-shot exemplars, and monitoring sensors. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Fill the context window with the most relevant, least redundant chunks.",
 "m": 8,
 "k": 3,
 "affinity": [
  9,
  9,
  8,
  7,
  4,
  3,
  6,
  5
 ],
 "redundancy": [
  [
   0,
   8,
   1,
   0,
   0,
   0,
   2,
   0
  ],
  [
   8,
   0,
   1,
   0,
   0,
   0,
   2,
   0
  ],
  [
   1,
   1,
   0,
   2,
   0,
   0,
   1,
   0
  ],
  [
   0,
   0,
   2,
   0,
   0,
   0,
   0,
   3
  ],
  [
   0,
   0,
   0,
   0,
   0,
   4,
   0,
   0
  ],
  [
   0,
   0,
   0,
   0,
   4,
   0,
   0,
   0
  ],
  [
   2,
   2,
   1,
   0,
   0,
   0,
   0,
   5
  ],
  [
   0,
   0,
   0,
   3,
   0,
   0,
   5,
   0
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "value": 21,
 "count": 3,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example rag_context_packing --format json | hexstellar solve select
curl -s https://api.hexstellar.com/api/v1/examples/rag_context_packing        # the full example over HTTP

Agriculture

🌱 Crop Rotation & Adjacency Planner

Agriculture · command rules · effort flash · id: agtech_crop_rotation

One exclusion primitive stamped on two axes: adjacent plots in one season, consecutive seasons in one plot — space and time, same rule.

Three plots in a row, two seasons, three crop families: tomato, legume, brassica. The rules of real rotation planning: adjacent plots must not both grow tomato in the same season (a pest bridge), no plot may repeat tomato or brassica in consecutive seasons (soil-borne disease persists), a supply contract pins tomato on plot 1 in season 1, and agronomy says a tomato season must be followed by a legume on the same plot (nitrogen replenishment). HexStellar returns the full space-time planting map: season 1 tomato-legume-legume, season 2 legume-legume-tomato — the contracted tomato is honored, the legume follows it as required, and the tomato slot migrates to plot 3 where neither adjacency nor succession blocks it. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

Node plot*6 + season*3 + crop (plots 0-2, seasons 0-1, crops 0=tomato, 1=legume, 2=brassica). answer[i] is 1 when that plot grows that crop that season. violations is 0 when every plot-season has exactly one crop and no adjacency, succession, contract, or agronomy rule is broken.

Where this shows up

Field crop rotation, greenhouse and vertical-farm zoning, orchard interplanting, land-lease planning — the same lattice also reappears wherever assignments must respect neighbors in SPACE and predecessors in TIME: exam timetabling, paint campaigns, kiln loading.

The same encoding also solves 8

  • Phased channel-group refarm across a cellular network without neighbour interferenceTelecom
    cells → cell sites; values → channel groups; periods → refarm phases; choose_one → each site runs exactly one group per phase; spatial exclusion → one rule per (overlapping-coverage pair, group) so two overlapping sites cannot hold the same group in a phase; temporal exclusion → one rule per (site, consecutive phase pair, group) so a site cannot keep a group across phases; force_true → the site its licence pins to a group; requires → a site moved off a group must land on the mandated successor group next phase
  • Bay-level planogram theming across promotional cyclesRetail
    cells → shelf bays; values → merchandise categories; periods → promotional cycles; choose_one → one category per bay per cycle; spatial exclusion → one rule per forbidden (neighbouring-bay, category-pair) combination, e.g. two cannibalising categories side by side; temporal exclusion → a bay cannot repeat one category two cycles running; force_true → the bay contracted to a supplier this cycle; requires → a full-price cycle in a bay implies the clearance category there next
  • Stocking and fallowing plan for net pens on a shared mooring gridAquaculture
    cells → net pens; values → stocked classes plus 'fallow'; periods → production cycles; choose_one → each pen holds exactly one class per cycle; spatial exclusion → neighbouring pens on one grid cannot hold the same class, which is the sea-lice bridge; temporal exclusion → a pen cannot restock the class it just harvested; force_true → the pen contracted to a harvest window; requires → a harvest class implies 'fallow' in that pen next cycle
  • Assigning firmware rollout waves to rack rows without exceeding a failure domain's blast radiusCloud infrastructure
    cells → rack rows; values → rollout waves plus 'no change'; periods → maintenance periods; choose_one → each row takes exactly one wave per period; spatial exclusion → two rows in one failure domain cannot take the same wave in a period; temporal exclusion → a row cannot be touched in consecutive periods; force_true → the row pinned by a customer's scheduled migration; requires → a row that took a wave implies 'no change' next period
  • Insecticide-class rotation across districts to delay vector resistancePublic health
    cells → districts; values → insecticide classes; periods → campaign rounds; choose_one → one class per district per round; spatial exclusion → bordering districts cannot use the same class in one round; temporal exclusion → a district cannot repeat a class in consecutive rounds, which is the resistance-rotation rule; force_true → a district pinned to a class by its outbreak protocol; requires → a class used implies the mandated follow-up class there next round
  • Adjacency-constrained harvest block scheduling under a green-up ruleForestry
    cells → cut blocks; values → clearcut / thin / leave; periods → planning periods; choose_one → one treatment per block per period; spatial exclusion → two blocks sharing a boundary cannot both be clearcut in one period; temporal exclusion → a block cannot be clearcut in consecutive periods; force_true → the block committed under a timber licence; requires → a clearcut implies 'leave' in that block next period
  • Campaign allocation on parallel lines sharing an air-handling zone under allergen segregationFood and pharma manufacturing
    cells → parallel production lines; values → product families plus 'clean-out'; periods → campaign periods; choose_one → one family per line per period; spatial exclusion → two lines on one air-handling zone cannot run an allergen-conflicting family pair in a period; temporal exclusion → a line cannot repeat an allergen family back to back; force_true → the line committed to a validated batch; requires → an allergen family implies 'clean-out' on that line next period
  • Street-works permit windows under junction conflicts and a reinstatement moratoriumMunicipal works
    cells → street segments; values → works classes plus 'no works'; periods → permit windows; choose_one → one class per segment per window; spatial exclusion → two segments sharing a junction cannot both be excavated in one window; temporal exclusion → a segment cannot be reopened in the next window; force_true → the emergency repair already permitted; requires → an excavation implies 'no works' in that segment next window

Measured at scale actually run

The same space-by-time lattice at 100,000 (plot, season, crop) booleans — 10,000 plot-seasons each taking one of ten crop families — under 30,000 adjacency, succession and contract rules returns a full planting map whose broken-rule count is certified minimal and independently checked.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical lattice at 400 plots, 6 periods and 12 families is 400 × 6 × 12 = 28,800 booleans with 2,400 choose_one rules. On a 20 × 20 field there are 760 adjacent plot pairs, so each conflicting family costs 760 × 6 = 4,560 spatial exclusions, and each non-repeatable family costs 400 × 5 = 2,000 temporal exclusions — one exclusion per pair per axis, exactly as in the 18-variable instance. The rule vocabulary never changes with size, and a violations count of 0 certifies the whole board rather than one period of it.

The encoding recipe (agent notes)

THE LESSON: one exclusion primitive, stamped across TWO different dimensions. A rotation plan is a lattice of (plot, season) cells, each with one-hot crop booleans plus choose_one. SPATIAL rules ('adjacent plots can't both host tomato') become mutual_exclusion instantiated on every ADJACENT-PLOT pair within each season; TEMPORAL rules ('no tomato after tomato') become mutual_exclusion instantiated on every CONSECUTIVE-SEASON pair within each plot. Same primitive, different axis — enumerate the pairs along each axis separately and don't miss one. Contracts are force_true; agronomy sequences ('tomato ⇒ legume next') are requires from the season-1 boolean to the specific season-2 boolean. COMMON MISTAKES: (1) writing the succession rule once instead of once PER PLOT, or the adjacency rule once instead of once per adjacent pair PER SEASON — rules are templates over the lattice, exactly like the map-tile grammar; (2) requires direction — [tomato_s1, legume_s2] means tomato-then-legume, not the reverse; (3) demand QUOTAS ('at least 50t of tomato across plots') need an at-least-k or weighted constraint that hard rules don't express — pin specific contracted cells with force_true as done here, or move volume targets to optimize; (4) the lattice grows as plots × seasons × crops — certify season windows in rolling chunks rather than one giant multi-year board. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Assign crops to plots across seasons so no pest bridge, soil-disease repeat, or agronomy rule is broken.",
 "n": 18,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1,
    2
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    3,
    4,
    5
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    6,
    7,
    8
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    9,
    10,
    11
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    12,
    13,
    14
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    15,
    16,
    17
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    6
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    3,
    9
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    6,
    12
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    9,
    15
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    3
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    2,
    5
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    6,
    9
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    8,
    11
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    12,
    15
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    14,
    17
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    0
   ]
  },
  {
   "type": "requires",
   "nodes": [
    0,
    4
   ]
  },
  {
   "type": "requires",
   "nodes": [
    6,
    10
   ]
  },
  {
   "type": "requires",
   "nodes": [
    12,
    16
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example agtech_crop_rotation --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/agtech_crop_rotation        # the full example over HTTP

Biotech

🧬 Biomarker Panel Selection

Biotech · command select · effort flash · id: bio_biomarker_panel

The value returned is signal minus redundancy paid, so a weaker uncorrelated marker can outrank a stronger one that duplicates a pick.

From twelve candidate biomarkers, choose exactly four for a diagnostic panel. Each marker has a diagnostic signal (affinity); correlated pairs carry a redundancy penalty, because two markers that say the same thing waste a slot. HexStellar picks the four that maximize total signal minus redundancy — a diverse, high-information panel. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is the chosen marker indices; value is total signal minus redundancy.

Where this shows up

Diagnostic panels, gene-signature selection, feature selection, sensor placement.

The same encoding also solves 8

  • Choose 15 of 800 factor signals for a live trading model where factors built on one data source explain the same returnFinance
    candidates → factor signals in the research library, k → factors the model's slot budget permits, affinity → out-of-sample information ratio attributed to that factor, redundancy → return-correlation overlap between a factor pair
  • Pick 30 of 1,200 substation PMU locations for a state-estimation network when units on the same bus observe the same stateEnergy / grid
    candidates → candidate PMU installation points, k → units the capital plan buys, affinity → observability added by that unit, redundancy → bus and branch observability shared by a unit pair; a hard requirement that every bus be observed at least once is not a term here, so state it with cover using min_cover
  • Choose 8 of 140 durability road-test routes for a validation programme when two routes load the chassis the same wayAutomotive
    candidates → proving-ground and public road-test routes, k → routes the validation programme schedules, affinity → damage-spectrum coverage of that route, redundancy → load-case content shared by a route pair
  • Pick 6 of 90 wheat breeding lines to advance to multi-location yield trials when lines from one cross carry the same trait packageAgriculture
    candidates → breeding lines from the nursery, k → lines the trial plots hold, affinity → selection index of that line, redundancy → pedigree and trait-package similarity between a line pair
  • Choose 12 of 400 spectral bands for a hyperspectral crop-stress product when adjacent bands carry the same reflectance informationEarth observation
    candidates → spectral bands the sensor can downlink, k → bands the product's data budget allows, affinity → classification information contributed by that band, redundancy → inter-band correlation between a band pair
  • Select 9 of 300 online analyzer measurements as inputs to an advanced process control model when analyzers on one column tray move togetherChemicals / process
    candidates → installed and proposed analyzer measurements, k → inputs the controller model accepts, affinity → control-relevant variance explained by that measurement, redundancy → measured collinearity between a measurement pair
  • Pick 25 of 600 hydrant and junction nodes for pressure-logger deployment when loggers in one district metered area record the same transientWater utility
    candidates → hydrant and junction nodes, k → loggers the deployment funds, affinity → leak-detection sensitivity at that node, redundancy → hydraulic zone shared by a node pair
  • Choose 16 of 500 candidate alloy compositions for a synthesis campaign when compositions near each other test the same hypothesisMaterials R&D
    candidates → compositions in the virtual library, k → samples the furnace campaign synthesizes, affinity → predicted property gain of that composition, redundancy → design-space proximity between a composition pair

Measured at scale actually run

Screening 2,000 candidate markers down to an 80-marker panel carries just 20,000 correlated pairs yet still fills an 11,729 KB request, because the redundancy matrix travels as a dense m x m block rather than as a pair list. The panel comes back marked heuristic (hypothesis — verify) rather than certified, so recompute its signal-minus-redundancy with the free verify call.

Instance
2,000 candidates · 80 k · 20,000 overlap pairs
Answer
heuristic (labelled)
Engine time
5 ms (4 ms–5 ms, n=3)
Peak memory
5.8 MB
Request
11,729 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only select --sizes target

How the encoding grows

The identical encoding at 2,500 candidate markers with a 20-slot panel is 2,500 affinity values and up to 3,123,750 distinct pairwise penalties (a 6,250,000-entry symmetric matrix), carried in one request still described by m, k, affinity, redundancy. Certification is proven by exhaustion and is stated on every answer, so at this size the result carries the heuristic label, while the returned panel contains exactly 20 markers.

The encoding recipe (agent notes)

THE ENCODING RECIPE: select takes candidates with an affinity (the value of picking each one), a redundancy matrix (a penalty on PAIRS that overlap), and k, the exact panel size. redundancy is a full symmetric m x m array — every row carries m entries, and pairs that do not overlap are simply 0; a sparse list of only the correlated pairs is rejected as invalid input (exit 3). COMMON MISTAKES: (1) greedy top-k by affinity — the whole point is that the 2nd and 3rd strongest markers may measure the SAME biology; the pairwise redundancy term is what forces complementary coverage (same shape as picking RAG passages or portfolio diversification); (2) reading value as raw signal — it is affinity gained MINUS redundancy paid, so a lower-affinity but uncorrelated marker can beat a stronger correlated one; (3) treating k as 'at most' — it is exact; if fewer is allowed, run k, k−1, … and compare value; (4) forgetting that ANY subset-with-overlap problem fits this shape: sensors, features, test items, ad slots, committee seats. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Pick the most informative, least redundant panel of markers.",
 "m": 12,
 "k": 4,
 "affinity": [
  9,
  8,
  7,
  8,
  6,
  9,
  5,
  7,
  8,
  6,
  7,
  5
 ],
 "redundancy": [
  [
   0,
   6,
   1,
   0,
   0,
   5,
   0,
   0,
   0,
   0,
   0,
   0
  ],
  [
   6,
   0,
   0,
   0,
   0,
   6,
   0,
   0,
   0,
   0,
   0,
   0
  ],
  [
   1,
   0,
   0,
   5,
   0,
   0,
   0,
   4,
   0,
   0,
   0,
   0
  ],
  [
   0,
   0,
   5,
   0,
   0,
   0,
   0,
   5,
   0,
   0,
   0,
   0
  ],
  [
   0,
   0,
   0,
   0,
   0,
   0,
   4,
   0,
   0,
   3,
   0,
   0
  ],
  [
   5,
   6,
   0,
   0,
   0,
   0,
   0,
   0,
   5,
   0,
   0,
   0
  ],
  [
   0,
   0,
   0,
   0,
   4,
   0,
   0,
   0,
   0,
   4,
   0,
   0
  ],
  [
   0,
   0,
   4,
   5,
   0,
   0,
   0,
   0,
   0,
   0,
   3,
   0
  ],
  [
   0,
   0,
   0,
   0,
   0,
   5,
   0,
   0,
   0,
   0,
   0,
   4
  ],
  [
   0,
   0,
   0,
   0,
   3,
   0,
   4,
   0,
   0,
   0,
   0,
   0
  ],
  [
   0,
   0,
   0,
   0,
   0,
   0,
   0,
   3,
   0,
   0,
   0,
   3
  ],
  [
   0,
   0,
   0,
   0,
   0,
   0,
   0,
   0,
   4,
   0,
   3,
   0
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "answer": [
  0,
  3,
  8,
  10
 ],
 "value": 32,
 "count": 4,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example bio_biomarker_panel --format json | hexstellar solve select
curl -s https://api.hexstellar.com/api/v1/examples/bio_biomarker_panel        # the full example over HTTP

🧬 Three-Way Epistasis Reduction

Biotech · command optimize · effort flash · id: bio_epistasis_triple

An auxiliary means 'A and B both on', so a three-way reward rides on one pair; the gadget scores 0, so energy is the true 3-body value.

Three mutations each carry a fitness cost of 5, but a large synergy of 20 unlocks only when all three co-occur — a genuine three-body (epistatic) interaction. The engine's objective is strictly PAIRWISE: it has no three-way term. The fix is the classic Rosenberg reduction: add one auxiliary boolean standing for 'mutations 0 and 1 are both present', pin it to that meaning with a penalty gadget, and hang the three-way reward on the pair (aux, mutation 2). HexStellar returns all four booleans on with objective −5, which is exactly the true three-body value (three costs of 5 minus the synergy of 20) — certified optimal at every effort, and confirmed by brute force over all 16 states. The auxiliary variable never lies: at the optimum it equals mutation0 AND mutation1. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[0..2] are the three mutations; answer[3] is the AUXILIARY variable, which is 1 exactly when mutations 0 and 1 are both 1 — it is bookkeeping, not biology, and must be dropped when reading the result. energy is the true objective of the original three-body problem (here −5), because the gadget contributes exactly 0 whenever the auxiliary is consistent.

Where this shows up

Epistatic mutation combinations, drug triples that only work together, three-way feature interactions, 'all three approvals present' policy rewards, coalition bonuses requiring three parties, any AND-of-three condition that must be scored — every higher-order (hypergraph) term reduced onto a pairwise engine.

The same encoding also solves 8

  • Choosing dopants for a catalyst whose activity only appears with one ternary combinationMaterials science
    the three interacting booleans → candidate dopants, per-item linear cost → loading and processing cost of each dopant, three-way reward → the measured ternary activity gain, auxiliary → 'dopants A and B are both present' (bookkeeping, stripped before the formulation is read), M → set above the activity gain it guards
  • Selecting process changes when a yield gain only appears if three ship togetherSemiconductor manufacturing
    the three interacting booleans → proposed process changes, per-item linear cost → qualification cost per change, three-way reward → the three-factor interaction effect measured in screening, auxiliary → 'changes A and B are both applied', M → above that interaction effect; design is the companion that chooses which runs resolve the interaction in the first place
  • Fitting avionics channels when a certification credit requires three dissimilar channels togetherAerospace
    the three interacting booleans → candidate channel implementations, per-item linear cost → mass and power budget consumed, three-way reward → the redundancy credit that exists only with all three fitted, auxiliary → 'channels A and B are both fitted', M → above the credit
  • Planning an intercropped plot where the yield bonus needs all three speciesAgriculture
    the three interacting booleans → species planted, per-item linear cost → seed and land cost per species, three-way reward → the measured polyculture yield gain, auxiliary → 'species A and B are both planted', M → above that yield gain
  • Choosing security controls when an audit clause only credits three deployed togetherSecurity and compliance
    the three interacting booleans → controls such as strong authentication, centralized logging and network segmentation, per-item linear cost → deployment and operating cost, three-way reward → the audit credit scored only when all three are live, auxiliary → 'controls A and B are both deployed', M → above the credit
  • Choosing pipe segments to renew when pressure only recovers if all three in the corridor are replacedWater infrastructure
    the three interacting booleans → segments in the renewal plan, per-item linear cost → capital cost per segment, three-way reward → the pressure and leakage benefit that appears only with all three renewed, auxiliary → 'segments A and B are both renewed', M → above that benefit
  • Composing a field crew when the job is only billable with all three certifications presentField service
    the three interacting booleans → candidate technicians, per-item linear cost → day rate, three-way reward → the job's billable value, credited only when the licensed, certified and language-qualified roles are all on the crew, auxiliary → 'technicians A and B are both assigned', M → above the billable value; if exactly one person per role is required, state that as a rules choose_one over each role's candidates and carry this gadget in the same request's linear and quadratic fields
  • Buying software modules when a rebate only unlocks on a three-module bundleEnterprise procurement
    the three interacting booleans → modules on the quote, per-item linear cost → list price per module, three-way reward → the bundle rebate, auxiliary → 'modules A and B are both on the order', M → above the rebate

Measured at scale actually run

Twenty thousand booleans — real decisions and their auxiliaries counted together — carrying 200,000 quadratic entries ship as a single 3,801 KB request. The label at that size is heuristic, not certified, so recompute the original three-body objective on the returned assignment and confirm it matches the reported energy.

Instance
20,000 variables · 20,000 linear terms · 200,000 pair terms
Answer
heuristic (labelled)
Engine time
112 ms (111 ms–119 ms, n=3)
Peak memory
17.2 MB
Request
3,801 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only optimize --sizes target

How the encoding grows

Each three-way term costs exactly one auxiliary variable, one linear entry and four quadratic entries (three for the gadget, one for the reward), so 200 real decisions carrying 500 declared triples submit as n=700 with 700 linear entries and 2,000 quadratic entries. A k-way term chains to k-2 auxiliaries, k-2 linear entries and 3(k-2)+1 quadratic entries — a five-way term is 3 auxiliaries and 10 quadratic entries — and because auxiliaries count toward n, they count toward whether the answer comes back certified by exhaustion or labelled heuristic.

The encoding recipe (agent notes)

THIS IS THE HIGHER-ORDER (HUBO → QUBO) REDUCTION — the technique that unlocks any k-way interaction on a pairwise engine (Rosenberg 1975; Boros & Hammer 2002). THE RECIPE: to score a term over x0·x1·x2, introduce an auxiliary y meant to equal x0 AND x1, and add the gadget M·(x0·x1 − 2·x0·y − 2·x1·y + 3·y) — which is exactly 0 when y = x0·x1 and strictly positive otherwise. In this API that is: linear {y: 3M}, quadratic [[x0,x1,M], [x0,y,−2M], [x1,y,−2M]]. Then hang the real reward on the PAIR [x2, y]. Chain the trick for k>3: reduce two variables at a time, each with its own auxiliary. COMMON MISTAKES: (1) trying to pass a 3-index entry like [0,1,2,−20] into quadratic — it takes [i, j, w] only, and a third index is a schema error, not a three-way term; (2) M TOO SMALL — if M does not exceed the reward the gadget guards, the solver 'cheats' by switching the auxiliary on without its parents to collect the reward; keep M comfortably larger than any reward touching the auxiliary (here M=25 vs reward 20), then verify by recomputing the ORIGINAL three-body objective on the returned assignment and checking it matches energy; (3) forgetting that the auxiliary is in answer — it inflates n and must be stripped before the result is read as biology (or business); (4) M ENORMOUS is also wrong — it crushes the real objective's dynamic range and makes every candidate look alike; size it just above the rewards it guards. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Score a three-way epistatic synergy (reward only when all three mutations co-occur) on a pairwise engine using one Rosenberg auxiliary variable.",
 "n": 4,
 "linear": {
  "0": 5,
  "1": 5,
  "2": 5,
  "3": 75
 },
 "quadratic": [
  [
   0,
   1,
   25
  ],
  [
   0,
   3,
   -50
  ],
  [
   1,
   3,
   -50
  ],
  [
   2,
   3,
   -20
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "energy": -5,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example bio_epistasis_triple --format json | hexstellar solve optimize
curl -s https://api.hexstellar.com/api/v1/examples/bio_epistasis_triple        # the full example over HTTP

💊 Resistance Pathway Coverage

Biotech · command cover · effort flash · id: bio_therapy_coverage

Hitting set is set cover read from the other side: list what each candidate covers. Pinned and barred are parameters, not costs.

A combination regimen must block five known resistance pathways. Six candidate agents each hit a distinct set of pathways — five hit a pair, and agent 5 hits three — at costs ranging from 4 to 9. Two decisions are already made before optimization starts: agent 1 is the standard of care and must be included, and agent 5 is ruled out for this patient population. HexStellar returns the cheapest regimen that respects both and still hits every pathway: agents 0, 1 and 3, cost 13. This is Hitting Set — the dual of Set Cover, and the same door. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer lists the agents in the regimen. uncovered counts pathways left unblocked; violations counts a forced agent left out or a forbidden agent slipped in. Both must be 0.

Where this shows up

Combination therapy against resistance, vaccine strain selection covering circulating variants, security-control selection covering every threat class, ingredient selection covering nutritional requirements, feature-flag bundles covering every tested scenario — plus any optimization where some decisions are already contractually fixed.

The same encoding also solves 7

  • Fortification blend covering every declared micronutrient with the mandated fortificant locked in and an allergen-bearing premix excludedFood Science
    sets → ingredients and premixes with the declared nutrients each one supplies, elements → nutrients the label must declare, min_cover → 1, cost → per-batch ingredient cost, force → the fortificant the national standard mandates, forbid → the premix excluded by allergen labelling (a per-nutrient dose in milligrams is a quantity, so a dose target belongs in milp)
  • Cryptographic suite covering every protocol requirement with the mandated primitive forced in and a deprecated cipher excludedCryptography
    sets → algorithm implementations and the protocol requirements each satisfies (key agreement, signature, AEAD, hash, per interop profile), elements → the protocol requirements, min_cover → 1, cost → code size plus certification cost of shipping that implementation, force → the primitive the compliance baseline mandates, forbid → the deprecated cipher
  • Newborn screening panel covering every notifiable condition with the statutory assay forced in and a withdrawn kit excludedPublic Health
    sets → assays and the screened conditions each one detects, elements → conditions on the mandated panel, min_cover → 1, cost → per-specimen reagent and interpretation cost, force → the assay the statute names, forbid → the recalled or withdrawn kit
  • Homologation lab selection covering every market regulation with the captive emissions lab forced in and a de-accredited lab excludedAutomotive
    sets → test labs and the market regulations each is accredited for, elements → regulations across the target markets, min_cover → 1, cost → the lab's test fee, force → the OEM's captive lab that must run emissions, forbid → the lab whose accreditation lapsed
  • Ancillary service procurement covering every reliability product with a must-run unit forced in and an outaged unit excludedPower Markets
    sets → generating units and the reliability products each can provide per zone (frequency response, reserve, black start), elements → the product-zone requirements, min_cover → 1, cost → the unit's contract price, force → the unit held under a reliability-must-run agreement, forbid → the unit on planned outage (megawatt volumes per product are quantities and belong in milp)
  • Translation vendor selection covering every target locale with the legal-terminology vendor forced in and one excluded by data residencyLocalization
    sets → vendors and the locales each one is qualified for, elements → target locales for the release, min_cover → 1, cost → the vendor's per-release fee, force → the vendor holding the legal-terminology contract, forbid → the vendor barred by the data-residency rule
  • Region set covering every residency and recovery requirement with the contracted primary region forced in and a sovereignty-barred region excludedCloud Infrastructure
    sets → candidate regions and the contractual requirements each one satisfies, elements → the requirements in the contract set, each one named (a residency jurisdiction, a recovery pairing with the contracted primary region, a support-hours window), min_cover → 1, cost → steady-state footprint price of standing that region up, force → the primary region already contracted, forbid → the region barred by sovereignty rules

Measured at scale actually run

At 4,000 candidate agents against 12,000 requirements to hit — 40,433 (agent, requirement) incidences in a single 261 KB request — the same encoding returned a regimen labelled heuristic, not certified, so re-price it with the free verify call, with any pinned agent still carried in that total at its real cost.

Instance
12,000 elements · 4,000 sets · 40,408 incidences
Answer
heuristic (labelled)
Engine time
872 ms (826 ms–876 ms, n=3)
Peak memory
16.7 MB
Request
261 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only cover --sizes target

How the encoding grows

At 1,500 candidate agents over 6,000 requirements the identical encoding is 1,500 booleans, 1,500 covered-element lists, one min_cover integer (or a 6,000-entry array of per-requirement demands) and a 1,500-entry cost array; force and forbid are index lists that subtract from the undecided set rather than add terms, so pinning 200 candidates and excluding 300 leaves 1,000 free booleans in the same request. Certainty is labelled per answer and certification is proven by exhaustion, so an instance that size returns a marked heuristic, and total_cost still carries the forced candidates at their real price.

The encoding recipe (agent notes)

DECISIONS ALREADY MADE ARE PARAMETERS, NOT COSTS. force pins candidates that must appear (standard of care, an already-signed contract, a regulatory requirement) and forbid removes candidates that are unavailable (allergy, recall, expired licence). COMMON MISTAKES: (1) simulating force with a huge NEGATIVE cost and forbid with a huge positive one — it usually works but it corrupts total_cost, which stops being the real price of the plan, so a downstream budget check silently reads a fiction; use the parameters; (2) forgetting that forcing changes what is optimal AROUND it — the forced agent already covers two pathways, so the cheapest completion is not the cheapest standalone cover; never pre-solve without the pin and patch it afterwards; (3) contradictions (an agent both forced and forbidden, or two forced agents listed as conflicting) are refused at the door by name — that is your model disagreeing with itself; (4) HITTING SET vs SET COVER: to block a pathway you need an agent that hits it, which is the same structure read from the other side — do not try to invert the matrix by hand, just list what each candidate covers. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Choose the cheapest combination of agents that blocks all five resistance pathways, including the mandatory standard-of-care agent and excluding one contraindicated candidate.",
 "sets": [
  [
   0,
   1
  ],
  [
   1,
   2
  ],
  [
   2,
   3
  ],
  [
   3,
   4
  ],
  [
   0,
   4
  ],
  [
   0,
   2,
   4
  ]
 ],
 "min_cover": 1,
 "cost": [
  5,
  4,
  6,
  4,
  5,
  9
 ],
 "force": [
  1
 ],
 "forbid": [
  5
 ]
}

Expected (engine-verified)

expected.json
{
 "total_cost": 13,
 "uncovered": 0,
 "violations": 0,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example bio_therapy_coverage --format json | hexstellar solve cover
curl -s https://api.hexstellar.com/api/v1/examples/bio_therapy_coverage        # the full example over HTTP

Cloud

🔗 Microservice Placement for Low Latency

Cloud · command qap · effort flash · id: cloud_microservice_latency

Cost lives in the pairs: set dist to (widest gap - gap) and 'keep these apart' becomes the same minimization as 'put these close'.

In a service mesh, the busiest traffic is service-to-service ('east-west'). Placing two chatty services in distant network zones injects latency into every request. HexStellar assigns each service to a placement slot so that the total RPC-traffic × network-latency is minimized — pulling the heavily-communicating pairs close together. For this size the placement is a certified optimum. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is a permutation: answer[i] is the slot assigned to service i. cost is total RPC×latency (lower means less aggregate east-west latency).

Where this shows up

Service-mesh and pod placement, NUMA/core pinning, cell/zone assignment, latency-aware scheduling.

The same encoding also solves 11

  • Exam timetabling that spreads conflicting exams apartEducation
    flow → number of students enrolled in both exam i and exam j, dist → closeness of periods a and b ((longest gap − gap between them), so a shared-student pair costs most when its periods are adjacent), answer[i] → the period for exam i; qap seats exactly one exam per period, so it is honest only for a one-exam-per-period schedule. The usual case — more exams than periods, several exams in one period — is rules: one binary per (exam, period), choose_one per exam, capacity_limit per period for the number of parallel rooms, and the same student-conflict x period-closeness products as quadratic terms
  • Seeding a knockout bracket so rivalries meet as late as possibleSports
    flow → how undesirable an early meeting between team i and team j is (rivalry or same-region score), dist → earliness of the round in which bracket positions a and b would meet ((rounds + 1) − that round), answer[i] → the bracket position for team i, cost → total conflict-weighted earliness; a fixed placement such as the top seed in a named position is a pin qap has no field for, so restate the same instance as rules: one binary per (team, position), choose_one per team and per position, force_true on the pinned (team, position) binary, quadratic = the same rivalry x earliness products
  • Frequency assignment where interference falls off with channel separationWireless networks
    flow → interference coupling between transmitters i and j, dist → (widest separation − separation between channels a and b), answer[i] → the channel for transmitter i; this is the one-transmitter-per-channel case. When more transmitters than channels must share the spectrum, the command is design: L sites = transmitters, K = channels, bonds = the interfering pairs, one shared KxK separation-cost table, per-site channel preferences in bias — note the table is shared by every bond, so design states which pairs interfere, not how strongly, and per-pair coupling weights do not survive the move
  • Patch-panel port assignment in a data hallNetwork cabling
    flow → number of cables (or aggregate bandwidth) between equipment i and equipment j, dist → cable-run length between patch positions a and b, answer[i] → the patch position for equipment i, cost → total cable length pulled
  • Laying out the vocabulary tiles on a child's speech-generating communication boardAssistive technology
    flow → how many times a day tile i and tile j are selected one straight after the other in the same utterance (counted from the device's own usage log), dist → the motor cost of moving from grid cell a to grid cell b for this user and this access method (finger reach, head-pointer travel, or number of scan steps), answer[i] → the grid cell that tile i is printed in, cost → total motor cost of a typical day's talking. The board is one page with exactly as many cells as tiles, so it is a clean permutation; when the therapist insists a learned core word keeps its corner, that pin is not a field qap has, so restate the same instance as rules: one binary per (tile, cell), choose_one per tile and per cell, force_true on the pinned (tile, cell) binary, quadratic = the same succession-count x cell-distance products
  • Assigning record series to shelf bays in an archive's closed stacksArchives and records management
    flow → how many reading-room requests pull series i and series j in the same visit (straight from the retrieval log), dist → trolley travel between bay a and bay b (aisle metres plus a fixed penalty for each lift transition), answer[i] → the shelf bay holding series i, cost → total trolley distance the retrieval staff cover in a year. qap seats exactly one series per bay, which is the accession-sized-run case; when one bay takes several small series, restate as rules: one binary per (series, bay), choose_one per series, capacity_limit k per bay for how many series that bay holds, quadratic = the same co-retrieval x bay-distance products
  • Positioning the prep stations in a new restaurant kitchenCommercial kitchen design
    flow → plates per hour handed directly from station i to station j at peak service (read off the ticket history of the existing kitchen), dist → steps between kitchen position a and kitchen position b, answer[i] → the kitchen position that station i is built into, cost → total steps the brigade walks in one service. Stations tied to a service drop — the fryer under the extraction hood, the pass at the window — are pins qap has no field for; restate as rules: one binary per (station, position), choose_one per station and per position, force_true on each fixed pairing, quadratic = the same handoff-rate x step-count products
  • Arranging the indicators on a nuclear control-room consoleNuclear power operations
    flow → how often indicator i and indicator j are read inside the same step of a procedure (counted across the plant's procedure set and simulator recordings), dist → the operator's head-and-hand travel between console position a and console position b, measured from the seated station, answer[i] → the console position that indicator i occupies, cost → total travel weighted by how often each pair is read together, which is exactly the quantity the human-factors review argues over
  • Placing the orchestra sections on the risers of a new concert hall stageOrchestral performance
    flow → how tightly section i has to lock to section j (count of cues and unisons between them across the season's repertoire, scored by the conductor), dist → the extra sound-path length between riser position a and riser position b, that is how much later one section hears the other, answer[i] → the riser position that section i sits on, cost → total coupling-weighted path difference across the whole ensemble
  • Assigning compartments to hull zones in a ship's general arrangementNaval architecture
    flow → crew trips per watch between compartment i and compartment j (from the manning and watch-routine study), dist → walking distance between hull zone a and hull zone b along the passages, with a fixed penalty per deck of ladder climbed, answer[i] → the hull zone that compartment i is drawn into, cost → total crew walking per watch
  • Siting the attractions on the plots of a new theme parkTheme park design
    flow → guests per day who ride both attraction i and attraction j in one visit (from ride-entry scans at the operator's existing parks), dist → path walking distance between build plot a and build plot b, answer[i] → the build plot that attraction i is built on, cost → total guest walking per day, the figure that then decides queue-line and vendor placement. An attraction pinned to a plot by services — the water ride on the plot with the main — is not a field qap has; restate as rules: one binary per (attraction, plot), choose_one per attraction and per plot, force_true on the pinned pairing, quadratic = the same co-ride x walking-distance products

Measured at scale actually run

At 200 services and 200 placement slots the request still carries just the two fields - 40,000 service-to-service RPC counts and 40,000 slot-to-slot latencies, 294 KB - and every service gets a slot. The label is heuristic: the east-west total is a hypothesis until the free verify call recomputes it independently.

Instance
200 variables · 40,000 flow entries · 40,000 distance entries
Answer
heuristic (labelled)
Engine time
26 ms (26 ms–26 ms, n=3)
Peak memory
3.0 MB
Request
294 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only qap --sizes target

How the encoding grows

At 60 placement slots the encoding is two 60x60 matrices — 7,200 numbers, 1,770 unordered pairs per matrix — and the cost is a sum of 3,540 traffic-by-distance products over one assignment out of 60! possible ones. The request keeps the same two fields it has at n=4; only the matrices get bigger. Certification is by exhaustion and is stated per answer, so a large instance returns a heuristic that says it is one.

The encoding recipe (agent notes)

SAME QAP SHAPE AS A LAYOUT PROBLEM, DIFFERENT STORY: flow[i][j] = RPC calls/sec between service i and j; dist[a][b] = network latency between slot a and slot b. Minimizing Σ flow·dist minimizes aggregate east-west latency. COMMON MISTAKES: (1) putting latency in flow and traffic in dist — traffic is over SERVICES, latency is over SLOTS; (2) reading answer as a yes/no placement — it's a one-to-one assignment (each slot holds one service); (3) forgetting that qap grows fast — keep the instance to the number of slots you actually have. TIP: whenever your problem is 'assign N things to N places and the cost depends on PAIRS of choices', it's QAP — not a linear assignment. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Co-locate chatty services so east-west latency is minimized.",
 "flow": [
  [
   0,
   500,
   50,
   20
  ],
  [
   500,
   0,
   200,
   10
  ],
  [
   50,
   200,
   0,
   300
  ],
  [
   20,
   10,
   300,
   0
  ]
 ],
 "dist": [
  [
   0,
   40,
   120,
   80
  ],
  [
   40,
   0,
   80,
   60
  ],
  [
   120,
   80,
   0,
   30
  ],
  [
   80,
   60,
   30,
   0
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "cost": 92400,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example cloud_microservice_latency --format json | hexstellar solve qap
curl -s https://api.hexstellar.com/api/v1/examples/cloud_microservice_latency        # the full example over HTTP

Culture

🖼️ Gallery Exhibit Selection

Culture · command rules · effort flash · id: museum_exhibit_selection

Conflicts are hard vetoes here, not prices — and without the exactly-k pin the empty set satisfies every one of them.

A temporary gallery has room for exactly three of six candidate works. Curatorial reality imposes pairwise conflicts: works 0 and 1 come from rival lenders, 0 and 2 fight for the same wall, 1 and 3 clash thematically. Two further pairs share a fragile-display case that can hold only one of each pair. HexStellar returns a set of exactly three mutually compatible works — a cardinality-constrained independent set (Karp 1972), which is a different beast from ranking works by merit: the third-best work may be unusable because of who else is in the room. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is 1 when work i is selected. violations is 0 when exactly three works are chosen and no conflicting pair or shared-case limit is broken. Several compatible trios can exist — test the invariant, not the specific trio.

Where this shows up

Exhibition and biennale curation, festival program selection, conflict-free committee formation, choreography phrase selection (movement phrases with incompatible transitions), sponsor placement, wine-flight or menu selection under clash rules — and drug-combination screening: pick exactly k drugs with no known adverse drug-drug interaction pair (the interaction graph's edges become the exclusions). In scientific computing the same shape picks k non-overlapping adaptive-mesh-refinement patches or k probe/sensor sites whose measurement volumes must not interfere. Astronomy's canonical version: assigning k spectrograph fibers to targets so no two fiber positioners collide (DESI/4MOST-style fiber assignment).

The same encoding also solves 8

  • Choosing which arms a site runs concurrently in a platform trialClinical research
    candidates → trial arms; choose_exactly k → arms the site can run at once; mutual_exclusion → an arm pair barred from co-enrolment by overlapping eligibility or a class-effect confound; capacity_limit k → arms drawing on one drug-supply lot
  • Assembling a reinsurance panel for one treaty layerInsurance
    candidates → reinsurers offered a line; choose_exactly k → the panel size the layer requires; mutual_exclusion → two carriers under one parent group, which the treaty forbids on the same layer; capacity_limit k → carriers already accumulating exposure in the same peril zone
  • Loading one air-cargo deck under dangerous-goods segregation rulesAir cargo
    candidates → consignments offered for the deck; choose_exactly k → positions to fill; mutual_exclusion → a dangerous-goods class pair the segregation table forbids on one deck; capacity_limit k → consignments needing the single active-cooling position
  • Selecting which subcontractor packages run inside one plant shutdown windowConstruction
    candidates → work packages; choose_exactly k → packages the window can hold; mutual_exclusion → two trades whose permits-to-work cannot both be open in one zone, such as hot works beside solvent handling; capacity_limit k → packages contending for the single crane
  • Picking reagents for a one-pot combinatorial screenChemistry
    candidates → reagents; choose_exactly k → reagents per well; mutual_exclusion → a reagent pair that reacts with each other rather than with the substrate; capacity_limit k → reagents requiring the one inert-atmosphere port
  • Seating a reviewer panel for a manuscript under a conflict-of-interest policyScholarly publishing
    candidates → reviewers; choose_exactly k → reviewers the editor must seat; mutual_exclusion → a co-author or same-institution pair the policy bars; capacity_limit k → reviewers already holding a competing submission this round. If expertise must be traded off rather than merely permitted, add linear weights to this same rule set; if a conflict is a price rather than a veto, select is the command that prices it.
  • Choosing which detection rules an endpoint agent enables within its rule budgetSecurity engineering
    candidates → detection rules; choose_exactly k → the rule budget the agent can run; mutual_exclusion → a rule pair that shadows one another's hooks and silently disables detection; capacity_limit k → rules contending for one kernel hook slot
  • Selecting guide RNAs for a multiplex editGenomics
    candidates → candidate guides; choose_exactly k → guides co-transfected in one construct; mutual_exclusion → a guide pair with predicted off-target overlap; capacity_limit k → guides sharing one barcode index

Measured at scale actually run

The same cardinality-pinned encoding at 100,000 candidate works across 10,000 exact-count slates, under 30,000 lender, wall and shared-case rules, returns a selection whose broken-rule count is certified minimal and independently checked — a zero there means the declared k really is compatible, and a positive count is the honest verdict that the conflict graph admits no such slate.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape at 5,000 candidates, 40,000 conflict pairs and 300 shared-resource groups is 5,000 booleans, one choose_exactly over all 5,000 nodes, 40,000 mutual_exclusion rules and 300 capacity_limit rules — 40,301 rules in one request, the same four rule types as the 6-variable gallery. The declared cardinality k stays exact at any size; a violations count of 0 certifies the chosen k break no conflict and no shared-resource cap, and a positive count is the diagnosis that the conflict graph admits no k-set, not an engine fault.

The encoding recipe (agent notes)

THIS IS INDEPENDENT SET WITH A CARDINALITY PIN — choose_exactly with k>1 over the WHOLE candidate list, plus one mutual_exclusion per conflict edge. Compare it to select: select trades soft pairwise redundancy against affinity (a bad pair costs points), while this makes the conflicts HARD (a bad pair is simply not a solution) and feasibility is the question. Use rules when conflicts are vetoes; use select when they are prices. COMMON MISTAKES: (1) encoding conflicts with requires — that builds a CLIQUE constraint (selected together), the exact opposite of keeping enemies apart; for 'these k must all be pairwise compatible' you exclude the NON-edges, for 'no conflicting pair' you exclude the edges — know which side of the graph you are constraining; (2) forgetting the exactly-k pin — without it the empty set satisfies every exclusion; choose_exactly k=3 is what forces the engine to navigate the conflict graph at all; (3) writing one exclusion per RULE instead of per PAIR — every conflict edge needs its own constraint; (4) if no compatible trio existed, violations would come back >0 — that is a diagnosis (the gallery is over-constrained: drop a conflict or reduce k), not an engine failure. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Choose exactly k works for a temporary gallery so no conflicting pair hangs together.",
 "n": 6,
 "constraints": [
  {
   "type": "choose_exactly",
   "k": 3,
   "nodes": [
    0,
    1,
    2,
    3,
    4,
    5
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    1
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    2
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    1,
    3
   ]
  },
  {
   "type": "capacity_limit",
   "k": 1,
   "nodes": [
    2,
    4
   ]
  },
  {
   "type": "capacity_limit",
   "k": 1,
   "nodes": [
    3,
    5
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example museum_exhibit_selection --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/museum_exhibit_selection        # the full example over HTTP

DevOps

🎨 Register Allocation Colorer

DevOps · command design · effort flash · id: compiler_register_allocation

One of K values per site natively, no one-hot: the request grows with the conflict count, not L×K, and a pin is just a bias on the rest.

Six variables are live in a hot function and the machine has three registers. The interference graph says which pairs are alive at the same time (including a triangle, so two registers can never suffice). The ABI pins variable 0 to register 0, and variable 5 prefers register 2. HexStellar assigns one register per variable with zero interference conflicts and both preferences honored — energy 0, certified optimal by exhaustion. This is graph coloring as it actually appears in compilers, radio planning, and timetabling: K choices per site, a shared cost table on every conflicting pair, and per-site preferences. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is the register (0..K-1) chosen for variable i. energy totals the pairwise table cost over all interference edges plus the bias of every chosen preference — 0 means a conflict-free coloring that also satisfies every preference. Note multiple perfect colorings can exist; test energy, not the exact assignment.

Where this shows up

Compiler register allocation, radio frequency assignment, exam and shift timetabling, PCB layer assignment, map coloring, wavelength assignment in optical networks — every 'K values per site, neighbors must differ' problem.

The same encoding also solves 6

  • Gate assignment when flights' ground times overlapAviation
    variables → flights, registers → gates, interference bond → a pair of flights whose occupancy windows overlap, table → identity x a clash cost so two overlapping flights at one gate is expensive, ABI pin → a widebody's large positive bias on every narrowbody-only gate, preference → a small POSITIVE bias on every gate that is NOT on the airline's home pier (penalize the values you do not want, as the base example does, rather than rewarding the one you do), energy 0 → a clash-free assignment that also honours every restriction. A negative reward bias is legal, but it moves the floor below 0 and then energy 0 is no longer the feasibility test.
  • Exam timetabling with shared studentsEducation
    variables → exams, registers → time slots, bond → a pair of exams sharing at least one enrolled student, table → identity x the clash cost (raise the off-diagonal too if back-to-back slots also hurt), pin → a large positive bias on every slot an exam cannot use, preference → a POSITIVE bias on every slot OTHER than the requested one, so 0 stays the floor and energy 0 still means feasible and preference-clean, energy 0 → no student is double-booked. A per-slot room capacity is not a design term - cap it with rules capacity_limit over the one-hot expansion, or post-check the slot counts.
  • Spreading a service's replicas across failure zonesCloud infrastructure
    variables → replicas, registers → availability zones, bond → a pair of replicas of the same service, table → identity x the co-location penalty, pin → a large positive bias on zones a data-residency rule excludes, preference → a POSITIVE bias on every zone OTHER than the one already holding that replica's data, keeping 0 as the floor, energy 0 → no two replicas of one service share a zone - reachable only when a service has no more replicas than there are zones; above that the same penalty still spreads them as evenly as the zones allow and the floor sits above 0.
  • Assigning PCB net segments to copper layersElectronics (EDA)
    variables → net segments, registers → copper layers, bond → a pair of segments whose routes would cross, table → identity x the short-circuit cost, with a graded off-diagonal where adjacent layers still couple, pin → a large positive bias on layers a high-current net may not use, preference → a negative bias on the layer carrying that net's test pad, energy 0 → no crossing pair shares a layer
  • Placing fixtures into broadcast windowsMedia
    variables → fixtures, registers → broadcast windows, bond → a pair of fixtures that genuinely cannot share a window (same stadium, or the same broadcaster's single slot) - table is ONE shared KxK cost applied to EVERY bond, so a soft audience overlap cannot be priced differently from a hard clash and does not belong in the same bond list, table → identity x the collision cost, pin → a large positive bias on windows a stadium curfew forbids, preference → a POSITIVE bias on every window OTHER than prime time for a marquee fixture, keeping 0 as the floor, energy 0 → nothing collides and every marquee preference is kept.
  • Assigning assays to instrument runs with carryover riskLife-science lab operations
    variables → assays, registers → instrument runs, bond → a pair of assays with cross-contamination risk, table → identity x the carryover cost, pin → a large positive bias on every run whose instrument lacks the required module, preference → a negative bias on the run that already has that reagent loaded, energy 0 → no risky pair shares a run

Measured at scale actually run

Two thousand simultaneously live variables competing for 8 registers across a 16,000-edge interference graph, carrying 1,000 pin-and-preference biases, is a 214 KB request that comes back with one register per variable. The answer is labelled heuristic, not certified, so re-sum the shared table over every interference edge plus each chosen bias with the free verify call before you call the coloring conflict-free.

Instance
2,000 items · 8 values · 16,000 bonds · 1,000 bias terms
Answer
heuristic (labelled)
Engine time
3 ms (3 ms–3 ms, n=3)
Peak memory
2.8 MB
Request
214 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only design --sizes target

How the encoding grows

The identical shape at 5,000 sites and 16 values is one L, one K, one bond per conflicting pair (a 40,000-edge interference graph is 40,000 entries), one 16x16 = 256-number symmetric table no matter how large L grows, and one bias triple per pin or preference — over K^L = 16^5000 assignments. The request scales with the CONFLICT COUNT, not with L x K: nothing one-hot is ever transmitted. Certification is by exhaustion and is reported per answer, so a large instance returns a labelled heuristic, and energy is recomputable from the returned assignment by summing the table over every bond plus the bias of each chosen value.

The encoding recipe (agent notes)

THE ENCODING RECIPE: design chooses one of K values PER SITE natively — L sites, not L×K booleans. bonds lists the conflicting pairs, table is one shared KxK cost applied on every bond (identity×10 here = 'same register on an interference edge costs 10'), and bias is sparse [site, value, energy] triples for pins and preferences (penalize the registers a variable must NOT take). COMMON MISTAKES: (1) hand-building the one-hot encoding in rules/optimize when the choice is K-ary — that multiplies variables by K and forces you to write choose_one everywhere; design is the native tool for coloring-shaped problems; (2) an ASYMMETRIC table — bonds are undirected, so table[a][b] must equal table[b][a] or the input is refused; (3) expecting one canonical coloring — permuting unpinned colors often yields equally perfect answers, so the invariant is energy (0 = feasible and preference-clean); decode and recompute the bond costs to verify; (4) values that live on a CYCLE (phases, directions, hues) — instead of a hand-written table, pass circular: {"j": J} for a cosine coupling where adjacent values are cheap and opposite ones expensive; (5) preferences vs pins — a pin is just a large bias against every other value, and if 'energy 0' matters to your test, make pins consistent with a feasible coloring or the floor rises above zero. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Give each live variable one of K registers so no two overlapping variables share one — K-ary coloring with pins and preferences.",
 "L": 6,
 "K": 3,
 "bonds": [
  [
   0,
   1
  ],
  [
   0,
   2
  ],
  [
   1,
   2
  ],
  [
   1,
   3
  ],
  [
   2,
   4
  ],
  [
   3,
   4
  ],
  [
   4,
   5
  ],
  [
   3,
   5
  ]
 ],
 "table": [
  [
   10,
   0,
   0
  ],
  [
   0,
   10,
   0
  ],
  [
   0,
   0,
   10
  ]
 ],
 "bias": [
  [
   0,
   1,
   5
  ],
  [
   0,
   2,
   5
  ],
  [
   5,
   0,
   2
  ],
  [
   5,
   1,
   2
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "energy": 0,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example compiler_register_allocation --format json | hexstellar solve design
curl -s https://api.hexstellar.com/api/v1/examples/compiler_register_allocation        # the full example over HTTP

📦 Dependency Version Resolver

DevOps · command rules · effort flash · id: devops_dependency_resolver

One boolean per component-version, choose_one per component: pin one with force_true and the requires edges cascade the whole fleet.

Upgrading a fleet means choosing one version per package under a web of rules: this package's new major requires that one's new major, and some versions are mutually incompatible. HexStellar picks a version for every package so no dependency is broken and no conflict is triggered — here it resolves a three-package graph with zero violations. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is one-hot per package: variable (package*2 + version) is 1 for the chosen version. violations is 0 when every choose-one, requires, and conflict rule holds.

Where this shows up

Dependency and version resolution, feature-flag consistency, IAM/config reconciliation, package-manager SAT solving — resolving a whole fleet to one coherent state instead of patching it piece by piece.

The same encoding also solves 7

  • Validating a vehicle option configuration before it reaches the order bankAutomotive
    packages → option families (engine, gearbox, trim, roof), versions → the variants offered in each family, choose_one → exactly one variant per family, requires → the engineering rule that the large engine forces the uprated brake package, mutual_exclusion → a homologation clash such as the panoramic roof with the roll cage, force_true → the variant the customer has already fixed
  • Assembling a multi-agent therapy regimen with one agent per drug classClinical pharmacology
    packages → the drug classes in the regimen, versions → the candidate agents within each class, choose_one → exactly one agent per class, requires → the rule that a given agent is used only alongside its pharmacokinetic booster, mutual_exclusion → two agents barred together by a documented interaction, force_true → the agent the patient is already established on
  • Specifying products so every tested fire and acoustic assembly stays certifiedConstruction
    packages → building assemblies (partition, glazed screen, roof build-up), versions → the certified products available for each, choose_one → exactly one product per assembly, requires → the tested-assembly rule that a fire-rated glazed screen is certified only with its tested frame, mutual_exclusion → a sealant and membrane pairing that voids the test, force_true → the product the architect has specified
  • Choosing modification variants so a set of supplemental type certificates stays validAviation
    packages → the aircraft systems being modified, versions → the approved variants per system, choose_one → exactly one variant per system, requires → the certificate rule that the new avionics suite forces the upgraded harness, mutual_exclusion → two certificates that cannot be installed on one airframe, force_true → the cabin configuration the operator has fixed
  • Choosing accounting method elections so a return stays internally consistentTax and accounting
    packages → the policy areas that carry an election, versions → the permitted methods in each area, choose_one → exactly one method per area, requires → a conformity rule such as electing LIFO inventory costing for tax forcing the same method in the financial statements, mutual_exclusion → two methods a statute bars together, such as the cash method alongside inventory-based accounting, force_true → a method locked in by a prior-year election
  • Choosing ingredient grades so every label claim survives the formulationFood manufacturing
    packages → formulation slots (emulsifier, sweetener, gelling agent) plus one binary variable per label claim, versions → the approved grades for each slot, choose_one → exactly one grade per slot, force_true → each claim the label actually makes, and the grade fixed by the brand specification, requires → the claim rule that the organic claim forces the certified grade of the emulsifier, mutual_exclusion → a grade barred together with a declared dietary claim
  • Resolving IP-block releases across an SoC so interface and process-kit revisions agreeChip design
    packages → the subsystems of the chip, versions → the IP-block releases available per subsystem, choose_one → exactly one release per subsystem, requires → the interface rule that a controller release forces the matching PHY release, mutual_exclusion → two blocks built against incompatible process-design-kit revisions, force_true → the CPU release the customer has pinned

Measured at scale actually run

Measured at 100,000 component-version variables under 30,000 declared requires and conflict rules in a 1,602 KB request, the same resolver encoding returned one coherent fleet-wide set of version choices, with its rule-violation count certified minimal and independently checked rather than left as an unlabelled guess.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape at 3,000 components averaging 8 candidate values is 24,000 binary variables and 3,000 choose_one groups, plus one requires per dependency edge and one mutual_exclusion per declared incompatibility, so 60,000 dependencies and 4,000 incompatibilities is 67,000 rules in one request. Only the counts grow, not the rule types, and violations is reported per answer: zero certifies that a coherent set of choices exists, while a positive count is a real unsatisfiable conflict surfaced before the change is applied.

The encoding recipe (agent notes)

DEPENDENCY RESOLUTION IS A LOGIC PROBLEM (this is what a package manager's SAT core does). 'Each package runs exactly one version' → choose_one over its per-version variables. 'A_v2 requires B_v2' → requires [A_v2, B_v2]. 'B_v2 is incompatible with C_v1' → mutual_exclusion [B_v2, C_v1]. 'We insist on the latest A' → force_true on A_v2, and the requires/conflict rules cascade the rest. COMMON MISTAKES: (1) requires direction — [A_v2, B_v2] means choosing A_v2 forces B_v2, not the reverse; (2) forgetting choose_one, which lets a package take zero or several versions; (3) a non-zero violations isn't a bug — it means the constraints are UNSATISFIABLE (a true dependency conflict), exactly what you want surfaced before you deploy. TO ADD A COST ('minimize the number of restarts', 'prefer fewer upgrades'), move to optimize and put a reward/penalty on each version choice. THE POINT: instead of upgrading one package and discovering the break at runtime, resolve the whole fleet to one coherent state up front. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Pick one version per package so every requires/conflicts rule holds at once.",
 "n": 6,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    2,
    3
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    4,
    5
   ]
  },
  {
   "type": "requires",
   "nodes": [
    1,
    3
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    3,
    4
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    1
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example devops_dependency_resolver --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/devops_dependency_resolver        # the full example over HTTP

🧷 CI Test Suite Selection

DevOps · command cover · effort flash · id: devops_test_selection

The cap counts chosen sets, not their weight: cheapest-first can strand a requirement, so the floor and the cap are one problem.

Seven product features must each be exercised by at least one regression suite. Six suites are available, each covering a different slice at a different runtime cost (in minutes), and the CI window fits at most three of them. HexStellar returns the cheapest legal selection: suites 0, 2 and 3 for 20 minutes, covering all seven features. The cheap-looking suites are a trap — greedily taking the two fastest leaves features uncovered and no third suite can rescue them, which is exactly why the count cap and the coverage floor must be solved together. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer lists the chosen suite indices. total_cost is the total runtime. uncovered counts features still untested and violations counts any other rule broken (here: exceeding the three-suite cap) — both must be 0.

Where this shows up

Regression-suite selection under a CI time box, smoke-test packs, audit sampling that must touch every control, monitoring checks under an alert budget, curriculum modules covering every learning objective in a fixed number of sessions.

The same encoding also solves 6

  • Tool crib loadout so every machined feature can be cut by a loaded tool within the turret's pocketsManufacturing
    sets → tools and the part features each one can cut, elements → features across the part family, min_cover → 1 (every feature has at least one loaded tool that makes it), cost → tool purchase plus regrind price, max_sets → number of turret pockets, one tool per pocket (a tool that occupies two pockets is a weighted budget and belongs in milp)
  • Asserted-claim selection for trial so every accused feature is read on, under the court's limit on asserted claimsLegal / IP
    sets → patent claims and the accused product features each one reads on, elements → accused features, min_cover → 1, cost → the invalidity-risk score assigned to asserting that claim, max_sets → the number of claims the scheduling order permits
  • Batch release-testing plan so every registered specification attribute is determined by a validated methodPharmaceutical QC
    sets → validated methods and the specification attributes each one determines, elements → registered attributes on the specification, min_cover → 1 (an attribute with a single registered method has exactly one candidate covering it, so it is selected by structure), cost → analyst and instrument charge per method, max_sets → the number of distinct method setups the lab's instrument schedule allows for this batch
  • Flight-test sortie selection so every certification requirement is demonstrated across the funded sortiesAerospace
    sets → sortie profiles and the certification requirements each demonstrates, elements → requirements in the compliance matrix, min_cover → 1, cost → fuel, crew and instrumentation charge per sortie, max_sets → the number of funded sorties
  • Planogram fill so every demand category is present on a fixture with a fixed number of facingsRetail
    sets → SKUs and the demand categories each one satisfies, elements → demand categories the fixture must serve, min_cover → 1, cost → holding cost of listing the SKU, max_sets → facings the fixture holds (a limit expressed in shelf centimetres instead of facings is milp)
  • Crop protection program so every scouted pest is controlled, with the program limited to a set number of productsAgriculture
    sets → registered products and the target pests each one controls, elements → pests in the scouting report, min_cover → 1, cost → product cost per hectare, max_sets → how many products the program will carry (per-product dose rates and application counts are quantities and belong in milp)

Measured at scale actually run

Scaled to 4,000 candidate regression suites over 12,000 product features — 40,433 (suite, feature) incidences in a single 261 KB request — the identical encoding returned a selection carrying the heuristic label rather than a certified optimum, so re-total the chosen suites' cost and re-read uncovered through the free verify call before treating it as the cheapest legal selection.

Instance
12,000 elements · 4,000 sets · 40,408 incidences
Answer
heuristic (labelled)
Engine time
872 ms (826 ms–876 ms, n=3)
Peak memory
16.7 MB
Request
261 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only cover --sizes target

How the encoding grows

At 2,500 candidate sets over 12,000 requirements the identical encoding is 2,500 booleans, 2,500 covered-element lists (50,000 (candidate, element) incidences at twenty each), one min_cover integer, a 2,500-entry cost array and a single max_sets integer — the count cap stays one number however large the universe gets, which is exactly why it cannot stand in for a weighted budget. Certainty is labelled on every answer, so a universe that size returns a marked heuristic, and uncovered still reports precisely how many requirements a cap that tight leaves unmet.

The encoding recipe (agent notes)

THE CAP AND THE FLOOR ARE ONE PROBLEM. min_cover is the floor (every feature tested at least once) and max_sets is a hard cap on HOW MANY candidates may be chosen — a count budget, not a weighted one. Solving them separately fails: pick cheap suites first and you can burn the budget before the hard-to-reach features are covered. COMMON MISTAKES: (1) treating the CI window as a weighted sum of minutes — max_sets counts SETS; if the real limit is 'total runtime under 25 min' that is a weighted knapsack and belongs in milp, while cost here only ranks candidates; (2) reaching for select with k=3 — it maximizes affinity minus redundancy and cannot guarantee a single feature is covered; (3) reading a shortfall as an engine failure — a cap that is genuinely too small makes the problem infeasible, and the door says so by returning uncovered>0 with a certainty line naming the COMBINATION as the culprit (a cap below the largest single-element demand is refused outright instead). CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Choose at most three regression suites so every one of seven features is covered at least once, minimizing total CI runtime.",
 "sets": [
  [
   0,
   1,
   2
  ],
  [
   2,
   3
  ],
  [
   3,
   4,
   5
  ],
  [
   5,
   6
  ],
  [
   0,
   6
  ],
  [
   1,
   4,
   6
  ]
 ],
 "min_cover": 1,
 "cost": [
  9,
  4,
  8,
  3,
  5,
  7
 ],
 "max_sets": 3
}

Expected (engine-verified)

expected.json
{
 "total_cost": 20,
 "uncovered": 0,
 "violations": 0,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example devops_test_selection --format json | hexstellar solve cover
curl -s https://api.hexstellar.com/api/v1/examples/devops_test_selection        # the full example over HTTP

Education

📝 Adaptive Test Item Selection

Education · command select · effort flash · id: cat_item_selection

Exposure control and content balance aren't extra constraints — both are the same pairwise penalty, so one overlap matrix buys you both.

A computerized adaptive test must choose a handful of items that maximize measurement information, but picking the top items by raw information over-exposes a few and clusters on one skill. HexStellar picks the set that maximizes total information minus overlap — informative AND spread across skills — here three items that skip the over-exposed, same-skill clusters. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is the chosen item indices; value is total information minus pairwise overlap; count is how many were selected.

Where this shows up

Computerized adaptive testing (CAT), item-exposure control, content balancing, question-bank rotation — high-stakes licensure, certification, and K-12 assessment.

The same encoding also solves 8

  • Choose 30 of 500 screened investigator sites for a phase III protocol where sites drawing on the same referral catchment compete for the same patientsPharma / Clinical trials
    candidates → screened investigator sites, k → sites the enrollment plan funds, affinity → projected enrollment at that site, redundancy → referral catchment shared by a site pair
  • Pick 6 of 120 screened applicants for an onsite loop so the shortlist spans distinct skill profiles rather than six near-copiesRecruiting / HR
    candidates → screened applicants, k → onsite loop slots, affinity → phone-screen score for that applicant, redundancy → skill-profile overlap between an applicant pair; a per-area minimum is not a term here, so impose it with rules choose_exactly or cover min_cover over the area groups
  • Pick the 5 opponent plays to drill in one practice block from 200 filmed plays when several plays exercise the same defensive readSports analytics
    candidates → filmed opponent plays, k → reps the practice block fits, affinity → expected points prevented by drilling that play, redundancy → defensive read shared by a play pair
  • Choose 20 of 400 wastewater sampling points for a pathogen surveillance network where points on one trunk sewer sample the same populationPublic health surveillance
    candidates → candidate sampling points, k → points the lab's assay throughput supports, affinity → population newly observed at that point, redundancy → upstream population shared by a point pair on the same trunk line
  • Select 8 of 150 drafted survey questions for a short instrument where several questions load on the same latent constructMarket research
    candidates → drafted survey questions, k → questions the completion-length limit permits, affinity → item-information contribution of that question, redundancy → latent-construct loading shared by a question pair
  • Pick 12 of 300 wafer test patterns for a production screen when patterns sensitize the same fault setSemiconductor test
    candidates → generated test patterns, k → patterns the tester's screen slot holds, affinity → faults detected by that pattern, redundancy → faults both patterns in the pair detect; a hard requirement that every fault be detected at least once is not a term here, so state it with cover using min_cover
  • Choose 4 of 60 approved simulator scenarios for a recurrent check when scenarios exercise the same failure modeAviation training
    candidates → approved simulator scenarios, k → scenario slots in the recurrent check, affinity → training value assigned to that scenario, redundancy → failure mode shared by a scenario pair
  • Pick 5 of 90 authored quests for a weekly event rotation when quests reuse the same zone and reward loopGame live-ops
    candidates → authored quests, k → quests in the weekly rotation, affinity → projected engagement per quest, redundancy → zone and reward-loop overlap between a quest pair

Measured at scale actually run

A 2,000-item bank drawn down to a form of exactly 80, under 20,000 non-zero same-skill and over-exposure penalty pairs, came back with all 80 items placed: the count is exact, while the optimality is only a labelled heuristic (hypothesis — verify) that the free verify call should re-score before a high-stakes form is published.

Instance
2,000 candidates · 80 k · 20,000 overlap pairs
Answer
heuristic (labelled)
Engine time
5 ms (4 ms–5 ms, n=3)
Peak memory
5.8 MB
Request
11,729 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only select --sizes target

How the encoding grows

The identical encoding at a 3,000-item bank with a 25-item form is 3,000 affinity values and up to 4,498,500 distinct pairwise penalties (a 9,000,000-entry symmetric matrix) in one request whose field list is unchanged: m, k, affinity, redundancy. The selected count is exactly 25 at any size, while certification is proven by exhaustion and is stated per answer, so a bank this large returns a labelled heuristic rather than a silent claim of optimality.

The encoding recipe (agent notes)

SAME select SHAPE AS BIOMARKER AND RAG PACKING, ASSESSMENT STORY: affinity is each item's information value at the learner's current ability estimate; redundancy is overlap — two items that probe the SAME skill (or are both over-exposed) penalize each other. Maximizing Σ affinity − Σ redundancy gives an informative, content-balanced, exposure-safe set. COMMON MISTAKES: (1) leaving redundancy empty → you get raw top-k, which over-exposes a few items and breaks test security; the overlap matrix IS the exposure/content control; (2) sign confusion — affinity rewards, redundancy penalizes; (3) treating k as a hard content quota per area — for strict per-area minimums you'd add those as separate constraints (or an optimize model). THE POINT: the same 'pick k, reward relevance, punish overlap' engine that assembles a diagnostic panel or a RAG context also builds a secure adaptive test. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Pick the most informative test items without over-exposing or over-covering one skill.",
 "m": 8,
 "k": 3,
 "affinity": [
  9,
  8,
  9,
  7,
  6,
  8,
  5,
  7
 ],
 "redundancy": [
  [
   0,
   7,
   1,
   0,
   0,
   6,
   0,
   0
  ],
  [
   7,
   0,
   0,
   0,
   0,
   7,
   0,
   0
  ],
  [
   1,
   0,
   0,
   5,
   0,
   0,
   0,
   4
  ],
  [
   0,
   0,
   5,
   0,
   0,
   0,
   0,
   5
  ],
  [
   0,
   0,
   0,
   0,
   0,
   0,
   4,
   0
  ],
  [
   6,
   7,
   0,
   0,
   0,
   0,
   0,
   0
  ],
  [
   0,
   0,
   0,
   0,
   4,
   0,
   0,
   0
  ],
  [
   0,
   0,
   4,
   5,
   0,
   0,
   0,
   0
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "value": 23,
 "count": 3,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example cat_item_selection --format json | hexstellar solve select
curl -s https://api.hexstellar.com/api/v1/examples/cat_item_selection        # the full example over HTTP

🎓 Adaptive Curriculum Sequencing

Education · command rules · effort flash · id: edtech_curriculum_path

Do not list the plan: force the goal only — its requires closure is implied, and the count cap decides whether that closure fits.

A learner wants to reach a goal topic, but every advanced module has prerequisites, and only so many modules fit in a term (cognitive load). HexStellar returns a plan that includes the goal, pulls in exactly the prerequisites it needs, and stays within the module budget — here reaching calculus by including its full prerequisite chain and nothing wasteful. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is 1 when module i is in the plan. violations is 0 when every prerequisite and load rule holds.

Where this shows up

Adaptive curriculum sequencing, learning-path generation, onboarding/upskilling plans, certification tracks — any 'reach this goal, respect the prerequisites, don't overload' program.

The same encoding also solves 8

  • Choosing which packages go into a hardened container base image when each package pulls in its declared dependenciesSoftware supply chain
    modules → packages; requires → a package's declared dependency, nodes [dependent, dependency]; capacity_limit k → the maximum component count the hardened image is allowed to carry; force_true → the application package the image exists to ship, which cascades its entire dependency closure in automatically
  • Scoping the minimum control set that closes a named audit finding this quarterSecurity compliance
    modules → security controls; requires → a control that cannot be deployed before its enabling control (disk encryption enforcement requires key escrow); capacity_limit k → controls the team can implement in the quarter; force_true → the control the audit finding names; optional linear weights on the same rule set → per-control effort, so the cheapest closure is preferred
  • Validating a configure-price-quote order for a machine with option interdependenciesIndustrial manufacturing
    modules → orderable options; requires → an option's enabling option (the hydraulic attachment requires the high-flow pump); capacity_limit k → installable option slots on the chassis; force_true → the customer's must-have option, which pulls its enablers into the build sheet
  • Assembling a pre-operative workup that fits the appointments available before the operating dateHealthcare delivery
    modules → tests and clearances; requires → a clearance that cannot be issued without its prior test (cardiac clearance requires the stress ECG); capacity_limit k → appointment slots before the operating date; force_true → the surgical clearance itself
  • Selecting which assembly, integration and test activities fit one cleanroom campaign before a shipment readiness reviewAerospace
    modules → AI&T activities; requires → a test that cannot run before the assembly step it verifies (vibration requires the harness install); capacity_limit k → activity slots in the cleanroom window; force_true → the shipment readiness review
  • Scoping a capital works programme where projects depend on enabling infrastructurePublic infrastructure
    modules → capital projects; requires → a project that cannot start without its enabling work (the tram extension requires the substation upgrade); capacity_limit k → projects the delivery organisation can run in one programme cycle; force_true → the project already committed in the approved budget
  • Planning a plasmid construct build where each construct depends on its intermediatesBiotech laboratory
    modules → cloning and assembly steps; requires → a construct that cannot be built before its intermediate; capacity_limit k → reactions the lab can run in one batch; force_true → the final construct the project exists to produce
  • Auto-generating a skill-tree build that reaches a target ability within the points the level grantsGame systems
    modules → skill-tree nodes; requires → a node that cannot unlock before its parent node; capacity_limit k → skill points available at this level; force_true → the target ability the build is being generated for

Measured at scale actually run

With 100,000 modules under 30,000 prerequisite, load-cap and goal rules, the study plan is returned with a violation count certified as the minimum, so a zero at that size proves the forced goal's entire prerequisite closure fits inside the declared cap.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape at 2,000 modules and 5,000 prerequisite links is 2,000 booleans, 5,000 requires rules, one capacity_limit over all 2,000 nodes and one force_true per goal — 5,002 rules in a single request, with the rule vocabulary unchanged from the 6-variable instance. Only the counts grow: a returned violations count of 0 certifies the plan breaks none of the declared rules, and a positive count identifies the budget as smaller than the forced prerequisite closure rather than reporting a silent guess.

The encoding recipe (agent notes)

PREREQUISITES ARE requires, LOAD IS capacity_limit, THE GOAL IS force_true. 'Module B needs module A first' → requires [B, A]; a chain (calculus needs algebra-advanced needs algebra-basics needs fractions) is one requires per link, and forcing the goal makes the WHOLE chain cascade in automatically. 'At most k modules this term' → capacity_limit. COMMON MISTAKES: (1) requires direction — [advanced, basic] means advanced⇒basic (advanced needs basic), not the reverse; get it backwards and the plan pulls in the wrong dependencies; (2) setting the load budget below the length of the forced prerequisite chain — then the goal can't be reached within budget and you'll see violations>0, which correctly tells you the term is too short; (3) expecting an ORDERING — this decides WHAT is in the plan, not the day-by-day sequence; for strict timing, add per-phase variables the way the scheduling examples do. THE REACH: the same requires+capacity+force_true shape plans employee upskilling, certification tracks, and onboarding — not just school. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Build a study plan that respects every prerequisite and fits the learner's load.",
 "n": 6,
 "constraints": [
  {
   "type": "requires",
   "nodes": [
    2,
    0
   ]
  },
  {
   "type": "requires",
   "nodes": [
    3,
    2
   ]
  },
  {
   "type": "requires",
   "nodes": [
    5,
    3
   ]
  },
  {
   "type": "requires",
   "nodes": [
    5,
    4
   ]
  },
  {
   "type": "capacity_limit",
   "k": 5,
   "nodes": [
    0,
    1,
    2,
    3,
    4,
    5
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    5
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example edtech_curriculum_path --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/edtech_curriculum_path        # the full example over HTTP

Energy

⚡ Microgrid Fault Islanding Reflex

Energy · command rules · effort flash · id: energy_microgrid_islanding

Measured reality enters as force_false, not a preference; the requires chain then eliminates every mode that needed it, unlisted.

A microgrid runs a generator (grid-tied, islanded, or shut down), a utility tie breaker, a hospital feeder, EV fast-charging, HVAC, and an industrial line. A fault is detected on the utility tie, so the tie breaker must stay open — which rules out grid-tied mode, because grid-tied operation requires the tie closed. The hospital must stay powered, and during the fault its bus is live only in island mode. The islanded generator can carry at most two of the three deferrable load blocks, and EV fast-charging and the industrial line share a feeder section that can carry only one of them. HexStellar returns the surviving topology: island the generator, keep the hospital, carry EV and HVAC, shed the industrial line — the electrical equivalent of a spinal reflex. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

Nodes 0-2 are the generator mode (grid-tied/islanded/shutdown, one-hot), node 3 the utility tie breaker (1 = closed), node 4 the hospital feeder, node 5 EV fast-charging, node 6 HVAC, node 7 the industrial line (1 = energized). violations is 0 when the chosen topology breaks no electrical or priority rule.

Where this shows up

Microgrid and campus-grid fault response, load shedding under generation loss, black-start sequencing, remote sites (islands, mines, polar stations) where the power system must restructure itself faster than an operator can react.

The same encoding also solves 8

  • Isolating a district metered area after a trunk main burstsWater utilities
    booleans → valves open and zones pressurized; choose_one → pump-station mode (mains-fed / reservoir-fed / off); force_false → the isolation valve pinned shut by the detected burst; force_true → the hospital supply zone that must stay pressurized; requires → mains-fed mode requires the trunk valve open, and the critical zone requires reservoir-fed mode during the isolation; capacity_limit k → non-critical zones the reservoir can hold; mutual_exclusion → two zones behind one pressure-reducing valve that cannot both be opened. The limit counts zones, not flow — group zones into comparable demand blocks, or move a true volumetric budget to milp.
  • Choosing the safe state of a process unit after a compressor tripOil and gas operations
    booleans → unit feeds and relief paths; choose_one → compressor state (normal / recycle / tripped); force_false → the tripped machine pinned off by the detected trip; force_true → the safety-critical utility that must keep running; requires → normal state requires the suction valve open; capacity_limit k → units routed to the one flare header; mutual_exclusion → two units sharing a relief header that cannot both relieve
  • Electrical reconfiguration and load shedding after an in-flight generator lossAviation systems
    booleans → bus-tie contactors closed and load groups powered; choose_one → supply mode for the remaining source (split / tied / APU); force_false → the failed generator's contactor pinned open; force_true → the flight-critical avionics bus; requires → tied mode requires the bus-tie contactor closed; capacity_limit k → non-essential load groups the remaining source carries; mutual_exclusion → galley and cargo heat on one feeder
  • Selecting a degraded drive configuration after an EV battery module isolatesAutomotive
    booleans → contactors closed and auxiliary loads powered; choose_one → drive mode (full / reduced / shutdown); force_false → the isolated pack contactor pinned open by the detected fault; force_true → steering and brake assist; requires → full drive mode requires the main contactor closed; capacity_limit k → comfort loads the reduced pack carries; mutual_exclusion → cabin heater and charge preconditioning on one high-voltage branch
  • Choosing an egress policy and traffic-class survival set after a transit circuit failsNetwork operations
    booleans → circuits up and traffic classes carried; choose_one → egress policy (primary transit / backup transit / peering-only); force_false → the failed circuit pinned down by the alarm; force_true → the emergency-services class; requires → primary-transit policy requires the failed circuit up, which is exactly what rules that policy out; capacity_limit k → non-priority classes on the remaining backup; mutual_exclusion → two classes that cannot share the single backup tunnel. The limit counts classes, not bits — size classes as comparable blocks, or model a real bandwidth budget with milp.
  • Reconfiguring an operating-theatre suite after a chiller lossHospital facilities
    booleans → zones held at specification and plant items running; choose_one → chiller plant mode (dual / single / free cooling); force_false → the failed chiller pinned off; force_true → the cardiac theatre that must hold pressure and temperature; requires → dual mode requires the failed unit available; capacity_limit k → air-handling zones the single chiller holds; mutual_exclusion → two zones on one AHU that cannot both be prioritized
  • Switching a payment switch to degraded authorization after an acquirer link dropsPayments infrastructure
    booleans → links up and merchant segments authorized online; choose_one → authorization mode (online / stand-in / floor-limit offline); force_false → the failed acquirer link pinned down; force_true → the scheme under a regulatory availability obligation; requires → online mode requires the acquirer link up; capacity_limit k → merchant segments the stand-in engine serves; mutual_exclusion → two segments bound to one HSM partition
  • Deciding which stations keep running after a robot cell faults on an assembly lineDiscrete manufacturing
    booleans → station enables; choose_one → robot cell mode (automatic / manual bypass / stopped); force_false → the faulted cell's enable pinned off; force_true → the safety interlock station that must stay live; requires → automatic mode requires the cell enable; capacity_limit k → stations the available operators can man; mutual_exclusion → two stations sharing one fixture

Measured at scale actually run

The same rule file at 100,000 breaker, mode and load booleans in 10,000 one-hot asset groups, under 30,000 declared preconditions, caps and measured pins, returns a surviving topology whose rule-violation count is certified minimal and independently checked — a 1.6 MB request answered inside 17 MB of peak memory, small enough to sit on the controller that has to act on it.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape on a campus with 600 switchable elements and 40 four-mode assets is 600 + 160 = 760 booleans and 40 choose_one rules; with 1,500 documented preconditions, 200 shared-section pairs, 40 generation groups and 30 measured pins that is 1,810 rules submitted as one request, using the same seven rule types as the 8-variable instance. The rule file is fixed for the site — between events only the force_true/force_false pins change — and a violations count of 0 certifies the returned configuration breaks none of the declared rules, while a positive count names the over-constraint, such as a must-serve load with no admissible mode.

The encoding recipe (agent notes)

THE ENCODING RECIPE: every breaker and load is a boolean (1 = closed/energized); an operating-mode choice is one-hot booleans plus choose_one. Detected reality is HARD: the fault makes the tie force_false, and critical service is force_true on the hospital. Electrical preconditions are requires — grid-tied mode requires the tie closed [0,3], and during the fault the hospital feeder requires island mode [4,1]. Shared-section and generation limits are mutual_exclusion and capacity_limit. COMMON MISTAKES: (1) modeling the fault as a preference instead of force_false — a reflex must treat measured reality as unbreakable, and the forced-open tie is exactly what propagates into 'grid-tied is impossible'; (2) requires direction — [0,3] means grid-tied ⇒ tie closed, not 'closing the tie forces grid-tied'; (3) forgetting force_true on critical loads — otherwise shedding the hospital is a perfectly valid way to satisfy every other rule; (4) capacity_limit counts NODES (at most k of these energized), not kilowatts — group loads into comparable blocks as done here, and move true weighted power budgets (sum of kW under a limit) to optimize/milp. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "A utility fault hits — decide in one shot which breakers, generator mode, and loads form the surviving electrical topology.",
 "n": 8,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1,
    2
   ]
  },
  {
   "type": "requires",
   "nodes": [
    0,
    3
   ]
  },
  {
   "type": "force_false",
   "nodes": [
    3
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    4
   ]
  },
  {
   "type": "requires",
   "nodes": [
    4,
    1
   ]
  },
  {
   "type": "capacity_limit",
   "k": 2,
   "nodes": [
    5,
    6,
    7
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    5,
    7
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example energy_microgrid_islanding --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/energy_microgrid_islanding        # the full example over HTTP

Engineering

◎ Pinned Inverse Completion

Engineering · command want · effort flash · id: design_pinned_completion

Pinned outputs remain fixed while the remaining variables minimize a recomputable objective.

Complete a coupled binary design while holding declared outputs fixed. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

check every pin then enumerate only free variables

Where this shows up

Materials, Operations, Physics

The same encoding also solves 3

  • Inverse material designMaterials
    required sites → pin
  • Policy completionOperations
    mandated decisions → pin
  • Boundary-conditioned modelPhysics
    fixed spins → pin

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Complete a coupled binary design while holding declared outputs fixed.",
 "n": 8,
 "field": {
  "0": -3,
  "4": 1
 },
 "couple": [
  [
   0,
   1,
   -5
  ],
  [
   1,
   2,
   -2
  ],
  [
   2,
   3,
   3
  ],
  [
   3,
   4,
   -4
  ],
  [
   4,
   5,
   2
  ],
  [
   5,
   6,
   -3
  ],
  [
   6,
   7,
   -2
  ]
 ],
 "pin": [
  [
   0,
   1
  ],
  [
   7,
   1
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "energy": -15,
 "pinned": [
  [
   0,
   1
  ],
  [
   7,
   1
  ]
 ],
 "feasible": true,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example design_pinned_completion --format json | hexstellar solve want
curl -s https://api.hexstellar.com/api/v1/examples/design_pinned_completion        # the full example over HTTP

Finance

📈 Portfolio Selection

Finance · command optimize · effort flash · id: finance_portfolio

Every reward is a negative weight and every correlation a positive pair penalty, so concentration is priced without any 'pick k' rule.

Eight assets, each with an expected return (the linear reward, entered as a negative because the engine minimizes). Correlated pairs carry a positive risk penalty in the quadratic term, so the engine avoids concentrating in assets that move together. HexStellar returns which assets to hold (1) or skip (0) — a Markowitz-style risk-adjusted basket as a QUBO. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is 1 to hold asset i, 0 to skip; energy is −return + risk (lower is better).

Where this shows up

Portfolio construction, index tracking, capital allocation, bet sizing.

The same encoding also solves 8

  • Media mix: choosing which paid channels to fund when two channels reach the same audienceAdvertising
    assets → paid channels, expected return → incremental conversions per unit of spend, correlation penalty → measured audience overlap between a channel pair, priced as the conversions both channels would claim
  • Feature selection for a credit scorecard whose predictors are multicollinearMachine learning
    assets → candidate features, expected return → univariate lift the feature adds to the score, correlation penalty → absolute pairwise correlation between two features, rescaled into the same lift units as the reward
  • Choosing which drug programs to fund when two share a biological target and fail togetherPharmaceutical R&D
    assets → development programs, expected return → risk-adjusted net present value, correlation penalty → shared-target failure covariance for a program pair
  • Siting wind farms when neighbouring sites generate and idle togetherEnergy
    assets → candidate sites, expected return → annual expected generation revenue, correlation penalty → output correlation between two sites in one wind regime, priced as the firmness the portfolio loses
  • Selecting reinsurance treaties when two treaties are exposed to the same catastrophe perilInsurance
    assets → treaties on offer, expected return → expected premium margin, correlation penalty → the accumulated exposure a treaty pair shares in one peril region
  • Choosing which exploration targets to drill when two test the same geological modelMining and exploration
    assets → drill targets, expected return → expected discovery value, correlation penalty → shared-model correlation for a target pair, priced as the value lost when one dry hole condemns both
  • Awarding a grant round when two proposals duplicate the same line of workResearch funding
    assets → proposals, expected return → panel merit score, correlation penalty → topic-overlap score between a proposal pair, priced as the duplicated award
  • Choosing store sites when two locations draw on the same catchmentRetail
    assets → candidate sites, expected return → forecast annual contribution, correlation penalty → trade-area overlap between a pair, priced as the sales one store takes from the other; if the rollout funds exactly k sites, select takes k natively, and a capital budget enters as a squared budget penalty that expands into the same linear and quadratic terms

Measured at scale actually run

A 20,000-asset universe carrying 200,000 retained correlation pairs is a 3,801 KB request that returns a hold-or-skip decision for every asset; at that size the answer is labelled heuristic rather than certified, so recompute the basket's energy — minus return plus risk — with the free verify call before it becomes a trade.

Instance
20,000 variables · 20,000 linear terms · 200,000 pair terms
Answer
heuristic (labelled)
Engine time
112 ms (111 ms–119 ms, n=3)
Peak memory
17.2 MB
Request
3,801 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only optimize --sizes target

How the encoding grows

The identical shape at 1,500 assets is 1,500 linear terms and, if every pair carries a penalty, 1,124,250 quadratic terms submitted as one request; real covariance inputs are thresholded, so keeping only the strongest 2% of pairs sends about 22,485 pair terms instead. Nothing about the structure changes with n — only how many numbers it holds — and the per-answer certainty label states whether the result was certified by exhaustion or is a heuristic to recompute with the free verify call.

The encoding recipe (agent notes)

THE ENCODING RECIPE: optimize MINIMIZES, so rewards enter as NEGATIVE linear terms (expected return −r on each asset) and risks as POSITIVE quadratic terms on correlated pairs. The engine then trades return against concentration automatically. COMMON MISTAKES: (1) the sign flip — entering returns as positive numbers makes the engine AVOID your best assets; every reward is negative, every penalty positive; (2) reading energy — it is −return + risk, so the net quality is its magnitude; recompute it from the raw problem to verify; (3) wanting 'exactly k assets' or a budget — plain linear+quadratic has no cardinality rule; add a big-M squared penalty (see the settlement-netting example) or use select, which takes k natively; (4) this shape is generic: any pick-a-subset problem with pairwise synergy or interference — server co-location, ingredient blending, team composition — is the same matrix with different labels. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Choose the basket that maximizes return while penalizing correlated risk.",
 "n": 8,
 "linear": {
  "0": -12,
  "1": -10,
  "2": -14,
  "3": -9,
  "4": -11,
  "5": -13,
  "6": -8,
  "7": -10
 },
 "quadratic": [
  [
   0,
   1,
   6
  ],
  [
   0,
   2,
   5
  ],
  [
   1,
   2,
   7
  ],
  [
   2,
   3,
   4
  ],
  [
   3,
   4,
   6
  ],
  [
   4,
   5,
   5
  ],
  [
   5,
   6,
   4
  ],
  [
   6,
   7,
   6
  ],
  [
   0,
   5,
   3
  ],
  [
   1,
   6,
   3
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "answer": [
  1,
  0,
  1,
  0,
  1,
  1,
  0,
  1
 ],
 "energy": -47,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example finance_portfolio --format json | hexstellar solve optimize
curl -s https://api.hexstellar.com/api/v1/examples/finance_portfolio        # the full example over HTTP

🏦 Settlement Netting Under Collateral Clashes

Finance · command optimize · effort flash · id: finance_settlement_netting

A forbidden pair is one positive weight larger than the smaller reward it guards; the settled value is minus the returned energy.

In a clearing cycle, each transaction can be settled or held. Settling a transaction is worth its notional value, but some pairs cannot both settle in the same cycle because they would clash on the same collateral. HexStellar picks the subset that maximizes total settled value while never paying a clash — here it settles three of six for a certified-optimal netted value. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is 1 when transaction i settles this cycle. energy is the minimized objective; the total settled value is its magnitude (−energy).

Where this shows up

RTGS/clearing-house netting, batch payment selection, any 'take the most valuable subset that never violates a pairwise conflict' decision.

The same encoding also solves 8

  • Filling a commercial break when two advertisers hold exclusivity against each otherBroadcast media
    transactions → bookable spots, notional value → the rate-card price of the spot, clash penalty → the exclusivity clause naming a pair that cannot air in the same break
  • Choosing which elective cases take one theatre day when two need the same single robot at overlapping slotsHospital operations
    transactions → requested cases, notional value → clinical priority score or reimbursement, clash penalty → a case pair whose booked slots overlap on the one shared robot
  • Picking which satellite passes a ground station records when passes overlap on one antennaSpace operations
    transactions → candidate passes, notional value → the data volume the pass returns, clash penalty → a pass pair that overlaps on the same antenna
  • Choosing which product batches run in one reactor campaign when two cross-contaminateChemical manufacturing
    transactions → candidate batches, notional value → batch contribution margin, clash penalty → a product pair whose changeover demands a full validated clean-out, so they cannot share the campaign
  • Accepting client mandates under conflict-of-interest rulesLegal services
    transactions → engagements on offer, notional value → expected fee, clash penalty → a pair sitting on opposite sides of the same matter in the conflicts register
  • Approving which maintenance outages run in one window when two jointly break N-1 securityElectric utility
    transactions → requested outages, notional value → the deferred-failure risk the outage removes, clash penalty → an outage pair that together leaves the corridor below N-1
  • Releasing orders into one pick wave when two orders claim the last unit of a SKUE-commerce fulfillment
    transactions → unreleased orders, notional value → order margin or promised-date urgency, clash penalty → a pair competing for the same serialized unit; when three or more orders compete, penalize every pair in the group, or state the group once as a rules mutual_exclusion
  • Allocating one night of telescope time among competing observing proposalsAstronomy
    transactions → submitted proposals, notional value → the allocation committee's merit score, clash penalty → a pair requesting the same instrument on the same night

Measured at scale actually run

A clearing cycle of 20,000 transactions with 200,000 recorded collateral clashes ships as one 3,801 KB request and comes back with an include-or-hold decision for the whole book, labelled heuristic rather than certified — so re-check the chosen transactions with the free verify call before the batch is released.

Instance
20,000 variables · 20,000 linear terms · 200,000 pair terms
Answer
heuristic (labelled)
Engine time
112 ms (111 ms–119 ms, n=3)
Peak memory
17.2 MB
Request
3,801 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only optimize --sizes target

How the encoding grows

A book of 5,000 transactions is 5,000 linear terms plus exactly one quadratic term per forbidden pair — conflicts are sparse, so 12,000 recorded clashes send 12,000 pair terms rather than the 12,497,500 a dense matrix would hold. The big-M rule is scale-free (each penalty only has to outweigh the smaller reward in the pair it guards, never a function of n), and each answer carries a certainty label saying whether it was certified by exhaustion or is a heuristic whose chosen pairs should be re-checked with the free verify call.

The encoding recipe (agent notes)

THE BIG PATTERN — 'BUSINESS RULE' = PENALTY, 'REWARD' = NEGATIVE WEIGHT. optimize MINIMIZES an energy. Model it with linear (a map of variable→weight) and quadratic (a list of [i, j, weight]). Put a REWARD as a NEGATIVE linear weight ('I want this, so choosing it lowers energy'). Put a CONSTRAINT 'A and B must not both be chosen' as a LARGE POSITIVE quadratic weight on the pair ('choosing both spikes the energy, so the solver avoids it'). This is the big-M trick: pick the penalty larger than any reward the pair could earn, but not astronomically large. COMMON MISTAKES: (1) sign flips — reward is negative, penalty is positive; getting it backwards makes the solver do the opposite; (2) a penalty too small to enforce the rule (it gets 'bought' by the reward) or so huge it flattens the landscape and slows the search — keep it a modest step above the larger reward in its own pair — the instance below uses 150, 140 and 90 against rewards topping out at 120; (3) reading energy as the settled value directly — it's the minimized objective, so the settled value is −energy. This one QUBO shape absorbs anti-affinity, incompatibility, cardinality and conflict rules across finance, cloud, and manufacturing. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Choose which transactions to settle to maximize netted value without a collateral clash.",
 "n": 6,
 "linear": {
  "0": -100,
  "1": -80,
  "2": -120,
  "3": -60,
  "4": -90,
  "5": -70
 },
 "quadratic": [
  [
   0,
   3,
   150
  ],
  [
   2,
   4,
   140
  ],
  [
   1,
   5,
   90
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "energy": -300,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example finance_settlement_netting --format json | hexstellar solve optimize
curl -s https://api.hexstellar.com/api/v1/examples/finance_settlement_netting        # the full example over HTTP

Gaming

🎮 Procedural Map Tile Consistency

Gaming · command rules · effort flash · id: game_procedural_map

A grammar rule is a template, not a constraint: stamp it on every adjacent pair in both directions, or unstamped pairs go unconstrained.

A world generator proposes a 2x3 chunk of terrain where every cell must become water, grass, or mountain. The tile grammar says water may never touch mountain (grass must buffer them). The designer has pinned a mountain in the northeast corner and a lake in the southwest corner, and map balance allows at most two water cells per chunk. HexStellar returns a complete tile assignment that satisfies the whole grammar at once — here the map GGM / WWG: grass buffers the pinned mountain from the pinned lake, and the second water lands beside the lake inside the budget. This is Wave-Function-Collapse-style generation with a global guarantee instead of local backtracking: the generator proposes, the engine certifies the world is legal before the player ever sees it. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

Cells are row-major on a 2x3 board (0-2 top row, 3-5 bottom row). Node cell*3 + t is that cell's tile candidate, t: 0=water, 1=grass, 2=mountain. answer[i] is 1 when that cell is locked to that tile. violations is 0 when every cell has exactly one tile and no adjacency rule, pin, or budget is broken.

Where this shows up

Procedural level and world generation, roguelike chunk streaming, puzzle solvability checking, live world repair after player actions — any content pipeline where generated output must be guaranteed legal, not just plausible.

The same encoding also solves 7

  • Exam timetabling where two exams sharing a student cannot land in the same slotEducation
    cells → exams, tile types → exam slots, choose_one → exactly one slot per exam, adjacent pair → a pair of exams with at least one student enrolled in both, forbidden tile combination → the same-slot pairing of that exam pair (one mutual_exclusion per slot), designer pin → an exam fixed by the registrar (force_true), water budget → the seat quota of a slot (capacity_limit over that slot's exam nodes)
  • Frequency assignment across transmitters with co-channel and adjacent-channel interferenceTelecom
    cells → transmitters, tile types → licensed channels, choose_one → one channel per transmitter, adjacent pair → two transmitters whose coverage overlaps, forbidden tile combination → the channel pairs that interfere on that overlap (same channel, or neighbouring channels), designer pin → a transmitter whose channel is fixed by licence (force_true), water budget → at most k transmitters on the shared guard channel (capacity_limit)
  • Hazardous-goods bay layout where incompatible chemical classes may not occupy neighbouring baysWarehousing
    cells → storage bays, tile types → chemical classes, choose_one → one class per bay, adjacent pair → two bays sharing a wall or an aisle, forbidden tile combination → the oxidiser/flammable class pairs banned as neighbours (stamped both ways), designer pin → a bay already loaded (force_true), water budget → at most k bays holding the class that needs spill containment (capacity_limit)
  • Routing-layer assignment where two crossing nets cannot share a layerElectronics
    cells → nets, tile types → routing layers, choose_one → one layer per net, adjacent pair → two nets whose footprints cross, forbidden tile combination → the same-layer pairing of a crossing pair (one mutual_exclusion per layer), designer pin → a pre-routed net (force_true), water budget → at most k nets on the impedance-controlled layer (capacity_limit)
  • Season planting plan where bordering parcels must not carry crops that bridge the same pestAgriculture
    cells → field parcels, tile types → crops, choose_one → one crop per parcel, adjacent pair → two parcels sharing a boundary, forbidden tile combination → the crop pairs that let a blight or pest cross that boundary, designer pin → a parcel already committed under contract (force_true), water budget → at most k parcels planted with the irrigation-heavy crop (capacity_limit over that crop's parcel nodes)
  • Register allocation where two simultaneously live values cannot share a physical registerCompilers
    cells → values needing a register, tile types → physical registers, choose_one → one register per value, adjacent pair → two values live at the same program point, forbidden tile combination → the same-register pairing of an interfering pair (one mutual_exclusion per register), designer pin → a value fixed by the calling convention (force_true), water budget → at most k values in callee-saved registers (capacity_limit)
  • Zoning a block where heavy industry may not abut residential without a commercial bufferUrban Planning
    cells → parcels, tile types → zoning classes, choose_one → one class per parcel, adjacent pair → two parcels sharing a boundary, forbidden tile combination → industrial directly beside residential (both directions), designer pin → a parcel with an issued entitlement (force_true), water budget → the cap on industrial parcels in the block (capacity_limit)

Measured at scale actually run

The same tile grammar at 100,000 (cell, tile) booleans over a 10,000-cell chunk of ten tile types, under 30,000 adjacency, pin and quota rules, returns a complete layout whose broken-rule count is certified minimal and independently checked — the whole chunk declared legal before a player ever walks into it.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape on a 128x128 chunk with 6 tile types is 98,304 booleans and 16,384 choose_one rules; its 32,512 four-neighbour cell pairs carry 65,024 mutual_exclusion rules for each forbidden label pair in the grammar (every pair stamped in both directions), plus one force_true per pinned cell and one capacity_limit per label quota — one request, same structure, larger numbers. Certification is reported per answer and is not decided by board size: a 100,000-boolean rule set carrying 30,000 rules has come back certified, so read the label the answer carries rather than assuming a bigger board must be a labelled heuristic.

The encoding recipe (agent notes)

THE ENCODING RECIPE: a tile CSP (Wave Function Collapse and friends) becomes one boolean per (cell, tile-type) plus a choose_one per cell. Each adjacency rule is stamped onto EVERY adjacent cell pair as mutual_exclusion in BOTH directions — here 'water never touches mountain' becomes two exclusions per neighboring pair. Designer pins and quest anchors are force_true; global balance budgets ('at most k water cells') are capacity_limit over that tile-type's nodes. COMMON MISTAKES: (1) writing one exclusion per RULE instead of per PAIR — a grammar rule is a template; it must be instantiated on every edge of the board's adjacency graph or distant cells will happily break it; (2) reading the returned layout as the only legal map — many maps can satisfy a grammar; the contract is violations = 0, so store and test the invariant, not the picture; (3) claiming playability from adjacency alone — 'the key is reachable from the start' is a PATH property, not an adjacency property; chain it explicitly with requires between region booleans or verify reachability upstream; (4) board size vs effort — this 2x3 chunk satisfies at every effort, but the same grammar on a 3x3 board already needs more than the lowest effort, so raise effort when a lower one still leaves violations — but board size does not decide the certainty label, and a single 100,000-boolean rule set has come back certified at the lowest effort, so read the label the answer carries rather than chunking a board to earn certification. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Lock every tile of a generated map so no adjacency rule, designer pin, or balance budget is broken.",
 "n": 18,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1,
    2
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    3,
    4,
    5
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    6,
    7,
    8
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    9,
    10,
    11
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    12,
    13,
    14
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    15,
    16,
    17
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    5
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    2,
    3
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    3,
    8
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    5,
    6
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    11
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    2,
    9
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    3,
    14
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    5,
    12
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    6,
    17
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    8,
    15
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    9,
    14
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    11,
    12
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    12,
    17
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    14,
    15
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    8
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    9
   ]
  },
  {
   "type": "capacity_limit",
   "k": 2,
   "nodes": [
    0,
    3,
    6,
    9,
    12,
    15
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example game_procedural_map --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/game_procedural_map        # the full example over HTTP

Healthcare

🏥 ICU Roster With Supervision & Fatigue Rules

Healthcare · command rules · effort flash · id: health_icu_roster

One variable per (person, slot): supervision is the same implication as precedence, fatigue an exclusion on one person's adjacent slots.

An ICU night roster has to obey human rules: a junior doctor may only be on shift if their supervising senior is also on; no one may work a night shift and then the next morning (fatigue); and certain doctors are already committed to the night. HexStellar returns a roster where every one of those rules holds at once — here with zero violations. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is 1 when that doctor-shift assignment is on. violations is 0 when every supervision, fatigue, and coverage rule holds.

Where this shows up

Nurse/physician rostering, shift supervision, apprentice pairing, any 'if the junior works, the senior must too' staffing dependency.

The same encoding also solves 6

  • Line-maintenance rostering where a mechanic may only be assigned a task if the licensed certifying engineer is on the same shiftAviation MRO
    binary variable → one (person, shift) assignment, requires [a,b] → mechanic assigned to shift S implies the certifying engineer assigned to S, mutual_exclusion → the same person on two shifts that break minimum rest, force_true → a shift already committed on the published roster, violations → the number of staffing rules broken by the returned roster
  • Court listing where a trainee magistrate may only sit a session the presiding judge also sitsJustice
    binary variable → one (judge, session) listing, requires → trainee listed on session S implies the presiding judge listed on S, mutual_exclusion → one judge listed in two courtrooms sitting at the same time, force_true → a hearing already fixed in the diary, violations → the number of listing rules broken
  • Plant permit-to-work scheduling where valve work in a window is authorised only if the upstream isolation is tagged out in that windowEnergy
    binary variable → one (work order, outage window) authorisation, requires → valve work in window W implies the isolation tag-out in W, mutual_exclusion → two work orders taking redundant trains out in the same window, force_true → an outage task fixed by the regulator's schedule, violations → the number of permit rules broken
  • Shooting-day scheduling where a minor's call day is legal only if the on-set tutor and chaperone are booked that dayFilm and TV production
    binary variable → one (person, shooting day) booking, requires → ONE RULE PER REQUIRED COMPANION: the minor booked on day D implies the tutor booked on D, and a second requires for the chaperone on D, mutual_exclusion → one performer booked to two units shooting the same day, force_true → a guest star's contractually fixed day, violations → the number of booking rules broken
  • Port transit planning where a deep-draft transit in a tide window is permitted only if an escort tug is booked for that windowMaritime ports
    binary variable → one (bookable item, tide window) booking, where a bookable item is a transit, a named escort tug, or a berth, requires → the transit booked in window W implies the NOMINATED escort tug booked in W - it must be a definite tug, because 'any one of several tugs' is an at-least-one rule that these rule types cannot state (nominate the tug first, or take at-least-k coverage to the cover command), mutual_exclusion → one tug booked to two transits sharing a window, force_true → a berth booking already contracted for a window, violations → the number of transit rules broken
  • Site works sequencing where a concrete pour in a week is released only if the rebar inspection is booked that weekConstruction
    READ IT AS SAME-WEEK RELEASE, NOT PRECEDENCE: binary variable → one (activity, week) release, requires → the pour released in week W implies the rebar inspection released in W, mutual_exclusion → one tower crane committed to two lifts in the same week (keep the granularity at the week the variables use), force_true → a pour week fixed by the supplier contract, violations → the number of release rules broken. 'The inspection happens in SOME week before the pour' is an at-least-one-of-several rule these types cannot state - declare the pair inside one week, or take the ordering to a sequencing command.

Measured at scale actually run

At 100,000 (clinician, shift) assignments governed by 30,000 supervision, fatigue and pre-commitment rules, the roster comes back with its violation count labelled certified minimum — certified meaning that count was independently re-checked, not that a plausible roster was accepted.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape at 120 clinicians across 21 shifts is 2,520 binary variables: fatigue is one mutual_exclusion per clinician per consecutive-shift pair (120 x 20 = 2,400 rules), plus one requires per supervision link and one force_true per pre-committed slot, all in a single request. Only the counts grow — the rule vocabulary stays at the same nine types — and violations is recomputed rule by rule from the returned assignment, so zero still certifies that every declared rule holds together.

The encoding recipe (agent notes)

requires MODELS SUPERVISION, NOT JUST TASK ORDER: requires with nodes [a, b] means 'if a then b' (a needs b). 'Junior Souza may only work if senior Lima works' is requires [Souza_night, Lima_night] — the SAME constraint type you'd use for task precedence, here expressing a staffing dependency. Fatigue ('not a night then the next morning') is mutual_exclusion. A doctor already committed is force_true. COMMON MISTAKES: (1) reversing requires — [junior, senior] means junior⇒senior, NOT senior⇒junior; get the direction right or the meaning flips; (2) expecting rules to enforce 'at least one intensivist on every shift' — that AT-LEAST-k coverage is not a current rule type (choose_one is EXACTLY one, capacity_limit is AT MOST k); model minimum-coverage with optimize for now; (3) reading violations>0 as a crash — it means the rules are jointly unsatisfiable (e.g. everyone is forced off), which is your cue to relax one. THE TRANSFER: the very same requires+mutual_exclusion+force_true shape schedules factories, courts, and airline crews. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Cover the shifts while a junior never works unsupervised and no one works back-to-back.",
 "n": 6,
 "constraints": [
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    1
   ]
  },
  {
   "type": "requires",
   "nodes": [
    2,
    3
   ]
  },
  {
   "type": "requires",
   "nodes": [
    4,
    5
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    2
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    0
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example health_icu_roster --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/health_icu_roster        # the full example over HTTP

🩺 Clinical Shift Coverage

Healthcare · command cover · effort flash · id: health_shift_coverage

A squared penalty punishes surplus as hard as shortfall, so the floor is declared per element; the family size is an output, not an input.

A ward must cover four shifts. Five staffing patterns are available: four of them cover two shifts each at a cost of 1, and the fifth covers three shifts at a cost of 2. Every shift needs at least one qualified person on it, and the ICU shift needs two. HexStellar returns the cheapest family of patterns that satisfies every requirement: total cost 3, with zero shifts short. This is Set Cover (Karp 1972) — and it is the regime hard rules cannot state: choose_exactly is exactly-k, capacity_limit is at-most-k, and 'at least k' is not a plain quadratic penalty, because (k−s)² would punish a shift that is over-covered exactly as hard as one left uncovered. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is the list of chosen pattern indices. total_cost is the summed cost of the chosen family (the minimized objective). uncovered is the number of shifts still short of their requirement and violations counts every OTHER rule broken (a ceiling, the max_sets cap, a forced/forbidden pattern, a conflict) — both must be 0 for a valid roster. certainty says whether this cost is proven optimal at this size.

Where this shows up

Nurse and physician rostering with minimum staffing per shift, on-call coverage, crew pairing, emergency-service station siting, sensor and camera placement with minimum redundancy, drug-target hitting sets, test-suite selection covering every requirement, warehouse pick-face assortment — every 'each requirement must be met at least k times, as cheaply as possible' problem.

The same encoding also solves 8

  • Conductor crew pairing where hazmat runs require a second qualified conductorRail
    sets → bid pairings, one row per crew member's itinerary, and the scheduled runs each one covers, elements → scheduled runs in the period, min_cover → 2 on runs that must carry a second qualified crew member (territory the assigned crew is not qualified over, so a pilot rides) and 1 on the rest, cost → credited pay of the pairing
  • Follow-the-sun on-call staffing where tier-1 payment blocks need two respondersSoftware Operations
    sets → rotation templates and the (service, block) requirements each one covers, elements → service blocks in the schedule grid, min_cover → 2 on tier-1 payment blocks and 1 elsewhere, cost → the on-call stipend the template costs
  • Harbour pilot duty patterns where LNG and deep-draft movements require two licensed pilotsMaritime
    sets → pilot duty patterns and the movement windows each one covers, elements → scheduled vessel movements, min_cover → 2 on LNG and deep-draft movements and 1 on the rest, cost → the pattern's pay plus launch charge
  • Branch shift patterns where dual-control vault operations require two authorized staffRetail Banking
    sets → shift patterns and the service blocks each one staffs, elements → service blocks the branch must staff, min_cover → 2 on dual-control vault blocks and 1 elsewhere, cost → wage cost of the pattern
  • Steward deployment where the away-supporter segregation block needs two stewardsLive Events
    sets → deployment patterns and the gates and stand blocks each one covers, elements → gates and stand blocks, min_cover → 2 on the segregation block and 1 elsewhere, cost → the shift cost of the deployment
  • Engine and lookout staffing where red-flag districts need two crews on coverWildland Fire
    sets → crew duty patterns and the district-blocks each one covers, elements → district-blocks needing response cover, min_cover → 2 on red-flag districts and 1 elsewhere, cost → the crew rate for the pattern
  • Court interpreter assignment where capital proceedings require team interpretingCourt Administration
    sets → interpreter availability blocks and the (session, language) requirements each can serve, elements → session-language requirements on the docket, min_cover → 2 for team-interpreted proceedings and 1 for the rest, cost → the booked rate for the block
  • Ground-station pass coverage where commissioning windows need two stationsSpace Operations
    sets → station schedule blocks, one row per station-block, and the required contacts each one has visibility to work, elements → the contacts the mission plan requires (satellite and orbit), min_cover → 2 on commissioning and maneuver contacts and 1 on routine passes, cost → the station booking price

Measured at scale actually run

A roster drawn from 4,000 staffing patterns against 12,000 shift requirements — 40,433 (pattern, requirement) incidences in one 261 KB request — comes back marked heuristic instead of certified, so the family of patterns it names and the cost it prices are a proposal, and the free verify call re-derives uncovered to say how many shifts are still short.

Instance
12,000 elements · 4,000 sets · 40,408 incidences
Answer
heuristic (labelled)
Engine time
872 ms (826 ms–876 ms, n=3)
Peak memory
16.7 MB
Request
261 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only cover --sizes target

How the encoding grows

At 3,000 candidate patterns over 9,000 coverage requirements the identical encoding is 3,000 booleans, 3,000 covered-element lists, a 9,000-entry min_cover array of per-requirement demands and a 3,000-entry cost array, submitted as one request; because each candidate is chosen at most once, a pattern that may be staffed by several teams is listed as that many candidate rows, so the boolean count is the number of fillable slots rather than the number of distinct templates. Certification is proven by exhaustion and labelled per answer, so a roster that size returns a marked heuristic with uncovered naming exactly how many requirements are still short.

The encoding recipe (agent notes)

THIS IS THE FOURTH COVERAGE REGIME, AND IT HAS ITS OWN DOOR. Pick by the requirement's verb: 'exactly once' → rules choose_exactly k=1 (exact cover); 'exactly k' → choose_exactly k; 'at most k' → capacity_limit; **'at least k' → this command.** THE ENCODING RECIPE: sets lists what each candidate COVERS (element indices), min_cover is the FLOOR per element (one integer for all, or an array for per-element demands), and cost prices each candidate. The booleans are the CANDIDATE PATTERNS, not the shifts — the same inversion exact cover uses. THE REST OF A REAL ROSTER IS ALSO NATIVE: max_cover is the CEILING per element ('at least two nurses, at most three' is min_cover 2 + max_cover 3); force pins patterns already contracted and forbid removes unavailable ones; conflicts lists [a,b] pairs that cannot both be used (two patterns needing the same person); max_sets caps how many patterns total. COMMON MISTAKES: (1) reaching for select — it picks exactly k items maximizing affinity minus redundancy, which answers a different question: it cannot guarantee any requirement is met, and here the family SIZE is an outcome, not an input; (2) hand-rolling at-least-k as an optimize penalty — (k−s)² punishes over-coverage as hard as under-coverage, so a correct hand encoding needs slack variables per element, which is exactly what this door builds for you; (3) forcing a pattern by giving it a huge negative cost — that works but distorts total_cost; use force; (4) confusing coverage COUNTS with weighted capacity — min_cover counts sets, not kilograms or watts; a weighted-sum budget still belongs in milp; (5) contradictions are refused UP FRONT and named (an element needing 2 covers that only 1 candidate contains, a floor above its ceiling, a set both forced and forbidden), so uncovered/violations > 0 in a RESULT means the search fell short — raise the effort — not that the problem is impossible. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Choose the cheapest set of staffing patterns so every ward shift is covered at least once and the ICU shift at least twice.",
 "sets": [
  [
   0,
   1
  ],
  [
   1,
   2
  ],
  [
   0,
   2
  ],
  [
   2,
   3
  ],
  [
   0,
   1,
   2
  ]
 ],
 "min_cover": [
  1,
  1,
  2,
  1
 ],
 "cost": [
  1,
  1,
  1,
  1,
  2
 ]
}

Expected (engine-verified)

expected.json
{
 "total_cost": 3,
 "uncovered": 0,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example health_shift_coverage --format json | hexstellar solve cover
curl -s https://api.hexstellar.com/api/v1/examples/health_shift_coverage        # the full example over HTTP

Infrastructure

🔁 HA Pair Config Sync & Failover

Infrastructure · command rules · effort flash · id: ha_failover_sync

Lockstep is identical on each value pair, so one force_false binds both units; exactly-one-active is different on the two role bits.

Two firewall units form a high-availability pair. Each runs exactly one of three firmware versions, and the pair must stay in lockstep: whatever version A runs, B runs. Version 0 has just been recalled — forbidding it on unit A must automatically forbid it on unit B through the sync rule, without writing the recall twice. Separately, the failover contract says exactly one of the two units holds the active role at any moment: not both (split-brain), not neither (outage). HexStellar returns a compliant state: both units on the same non-recalled version, one active, one standby. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

Nodes 0-2 are unit A's firmware version (one-hot), 3-5 unit B's, node 6 = 'A is active', node 7 = 'B is active'. violations is 0 when both units run the same permitted version and exactly one is active.

Where this shows up

HA firewall/load-balancer pairs, database primary-replica role assignment, RAID controller sync, dual-redundant avionics (synced config, single command authority), blue-green deployments where the two colors must match everywhere except which one serves traffic — and paired study design: matched case-control arms or twin cohorts that must receive identical protocol settings, with exactly one arm carrying the intervention flag.

The same encoding also solves 7

  • Bus-tie transfer between two utility feeders in a substationEnergy
    unit A's one-hot value group → feeder A's transformer tap position, unit B's group → feeder B's tap position, identical link per value → the pre-transfer rule that both sections sit on the same tap, force_false → a tap locked out by the protection study, different on the two role bits → which feeder is closed onto the bus (both closed parallels two sources, neither closed is an outage)
  • Main and backup playout chains on one encoding profile with exactly one on airBroadcast
    one-hot group per unit → the encoding profile loaded in the main and the backup encoder, identical link per profile → the requirement that a cut between chains not change the profile mid-stream, force_false → a profile withdrawn after a codec defect, different on the role bits → which chain feeds the transmitter (both is a double feed, neither is dead air)
  • Active-passive exchange gateway pair holding a single order-entry sessionFinance
    one-hot group per unit → the certified exchange protocol version on each gateway, identical link per version → the venue rule that a failover must not change protocol mid-session, force_false → a version decertified by the venue, different on the role bits → which gateway owns the order-entry session (two sessions duplicate orders, none stops trading)
  • Dual infusion pumps sharing one drug-library revision with a single delivering pumpMedical devices
    one-hot group per unit → the drug-library revision loaded on each pump, identical link per revision → the pharmacy rule that a swap must not change the dose limits, force_false → a revision pulled by a safety recall, different on the role bits → which pump is delivering and which is standby
  • Redundant PLC pair on a packaging line with one field-bus write tokenManufacturing
    one-hot group per unit → the program revision in each controller, identical link per revision → the hot-standby rule that both carry the same program before takeover, force_false → a revision held by change control, different on the role bits → which controller holds the field-bus write token (two writers collide, none halts the line)
  • Dual-channel brake-by-wire controllers on one calibration set with a single arbitration masterAutomotive
    one-hot group per unit → the calibration dataset flashed to each channel, identical link per dataset → the rule that the monitor channel validates against the same calibration as the commanding one, force_false → a dataset revoked by a field-safety campaign, different on the role bits → which channel is arbitration master and which is monitor
  • Enforced build diversity in a redundant safety pair, where the two channels must NOT run the same buildSecurity
    one-hot group per unit → the software build loaded on each channel, identical link per build → replaced by mutual_exclusion on each same-build pair, which forbids the two channels sharing a build (the diversity variant of the same skeleton), force_false → a build barred by an advisory, different on the role bits → which channel holds command authority

Measured at scale actually run

The same lockstep-and-exclusivity encoding has been measured on 100,000 firmware and role variables under 30,000 declared sync, recall and role rules in a single 1,602 KB request, and the pair state it returned carries a rule-violation count that is certified minimal and independently checked.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

At 500 redundant pairs drawn from a 12-value catalogue the identical shape is 2x12 + 2 = 26 variables per pair, 13,000 binary variables in one request, and 15 rules per pair (two choose_one groups, twelve identical links, one different on the role bits) for 7,500 rules. A withdrawn value is stated once per pair as a single force_false because the identical links carry it to the partner, and violations is reported per answer, so zero violations certifies that every declared rule holds rather than leaving an unlabelled guess.

The encoding recipe (agent notes)

TWO PRIMITIVES DO ALL THE WORK, AND AGENTS ALMOST NEVER REACH FOR THEM. Lockstep is identical on each version pair ([A_v, B_v] for every v): it makes the two one-hot groups mirror each other, so a fact stated once — force_false on A's recalled version — PROPAGATES to B through the identity, no duplication. Failover is different on the two role bits: [A_active, B_active] means exactly one is true, which is precisely 'one active, one standby' — no split-brain, no dead pair. COMMON MISTAKES: (1) simulating sync with two requires ([A_v,B_v] and [B_v,A_v]) — it works but doubles the constraints and hides the intent; identical IS the mirror; (2) using different on one-hot MEMBERS to mean 'not the same version' — on two one-hot groups that forces contradictions (it demands exactly one of each pair be true across ALL values); 'must differ' between one-hot groups is mutual_exclusion per same-value pair instead; different belongs on paired ROLE/state bits like active/standby; (3) writing the recall on both units — redundant once identical links them, and a maintenance hazard when the second copy is forgotten; state each fact once and let the identities carry it; (4) the diversity variant — 'the backup must run a DIFFERENT version than the primary' (defense against a bad release) is the same skeleton with the identities replaced by per-version mutual exclusions. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Keep a redundant pair on identical firmware while exactly one node holds the active role — sync and failover as two primitives.",
 "n": 8,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1,
    2
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    3,
    4,
    5
   ]
  },
  {
   "type": "identical",
   "nodes": [
    0,
    3
   ]
  },
  {
   "type": "identical",
   "nodes": [
    1,
    4
   ]
  },
  {
   "type": "identical",
   "nodes": [
    2,
    5
   ]
  },
  {
   "type": "force_false",
   "nodes": [
    0
   ]
  },
  {
   "type": "different",
   "nodes": [
    6,
    7
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example ha_failover_sync --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/ha_failover_sync        # the full example over HTTP

🛡️ Fault-Domain Partitioning

Infrastructure · command maxcut · effort flash · id: infra_fault_domain_split

Weight a pair by what a shared failure costs; cut_value is coupling separated, and coupling left inside a domain is total minus cut_value.

Seven components are connected by weighted couplings (shared state, chatter, dependency strength). HexStellar splits them into two fault domains so that the total weight of couplings crossing the boundary is as large as possible — which pulls the most tightly-coupled pairs into separate domains, so no single domain concentrates a dense cluster whose failure cascades. For a graph this size the split is a certified optimum. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is the domain (0 or 1) of component i. The 0/1 labels are arbitrary and can be flipped — what matters is who shares a domain. cut_value is the total weight crossing the boundary (higher = more coupling separated).

Where this shows up

Availability-zone and rack partitioning, blast-radius reduction, service mesh segmentation, sharding to spread hot dependencies. HPC domain decomposition is the same cut: partition a simulation mesh or particle set across two nodes so the heavy-communication pairs land on the fast intra-node link (the cut separates what must not share a slow boundary).

The same encoding also solves 7

  • Randomizing a matched cohort into treatment and control so each closely matched pair lands on opposite armsClinical research
    nodes → enrolled subjects, edge weight → the covariate-similarity score of that pair, answer[i] → the arm subject i is assigned to, cut_value → the matched similarity split across the two arms (higher = the two arms look more alike)
  • Dividing a catastrophe-exposed policy book between two reinsurance treaties so correlated policies never concentrate in one treatyInsurance
    nodes → policies, edge weight → the modelled loss correlation of that pair under a shared peril (same flood zone, same wind band, same fault line), answer[i] → the treaty policy i is ceded to, cut_value → correlated exposure separated; the exposure still concentrated inside one treaty is total edge weight - cut_value
  • Ground state of an antiferromagnetic Ising spin glass on an arbitrary interaction graphCondensed-matter physics
    nodes → spins, edge weight → the antiferromagnetic exchange J_ij of that bond, answer[i] → the orientation of spin i (0/1 relabelled to -1/+1), cut_value → the weight of anti-aligned bonds, so the energy sum J_ij s_i s_j equals (sum of all J_ij) - 2 * cut_value
  • Splitting a review committee into two parallel panels so no pair with a declared conflict of interest sits on the same panelScientific peer review
    nodes → reviewers, edge weight → the conflict severity of that pair (co-authorship count, shared affiliation, shared funder), answer[i] → the panel reviewer i joins, cut_value → conflict weight separated, with the conflict still left inside a panel equal to total edge weight - cut_value. A reviewer pinned to a named panel is a constraint this command has no field for: carry the same weights into rules and add force_true/force_false on that reviewer
  • Assigning redundant line-replaceable units to two independent aircraft channels so units sharing a failure cause are never on one channelAvionics
    nodes → redundant units, edge weight → the common-cause coupling of that pair (same supplier lot, same data bus, same cooling loop), answer[i] → the channel unit i is wired into, cut_value → common-cause coupling split across the two channels
  • Forming two teams from a lobby so habitual duo partners and same-clan players are placed on opposite sidesGaming
    nodes → players in the lobby, edge weight → that pair's togetherness score (matches played together, clan membership, party link), answer[i] → the team player i joins, cut_value → togetherness broken up across the two teams
  • Dual-sourcing a component list across two suppliers so parts sharing one upstream fab or port cannot fail togetherSupply chain
    nodes → purchased components, edge weight → the shared-upstream exposure of that pair (same wafer fab, same port of exit, same scarce input), answer[i] → which of the two suppliers is awarded component i, cut_value → shared exposure separated across the suppliers

Measured at scale actually run

At 8,000 components and 80,000 measured couplings the identical encoding is a single 1,314 KB request that returns one 0/1 domain label per component. That answer comes back labelled heuristic rather than the certified optimum the seven-component instance shipped here carries, so re-sum the weights whose two endpoints landed in different domains, or send it to the free verify call, before you quote its cut_value.

Instance
8,000 variables · 80,000 edges
Answer
heuristic (labelled)
Engine time
5.8 s (5.3 s–6.1 s, n=3)
Peak memory
69.6 MB
Request
1,314 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only maxcut --sizes target

How the encoding grows

The identical shape at 5,000 components is one integer n and one [i, j, weight] triple per measured coupling — 50,000 triples for a mesh averaging 20 couplings each, 12,497,500 for a fully measured matrix — submitted as one request, with the answer still one 0/1 domain label per component. Only the edge count grows, not the structure; certification is proven by exhaustion and reported per answer, so a graph that size returns a labelled heuristic whose cut_value you recheck by summing the weights whose two endpoints carry different labels.

The encoding recipe (agent notes)

WHAT MAX-CUT ACTUALLY MAXIMIZES: it finds the two-way split whose crossing edge weight is largest — i.e. it SEPARATES heavy edges. Model each coupling as an edge [i, j, weight]; a bigger weight is a stronger reason to keep that pair in different domains. COMMON MISTAKES: (1) expecting a fixed labeling — the answer is symmetric, so [0,1,0,...] and [1,0,1,...] are the same partition; compare groupings, never raw labels; (2) wanting the opposite objective — if your goal is to keep coupled pairs TOGETHER and cut as little as possible (classic min-cut / clustering), max-cut is the wrong tool for that framing; (3) omitting weights — an unweighted edge defaults to weight 1, which flattens strong and weak couplings. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Split tightly-coupled components into two domains so the heaviest links straddle the boundary.",
 "n": 7,
 "edges": [
  [
   0,
   1,
   7
  ],
  [
   1,
   2,
   5
  ],
  [
   2,
   3,
   8
  ],
  [
   3,
   0,
   6
  ],
  [
   0,
   4,
   3
  ],
  [
   4,
   5,
   9
  ],
  [
   5,
   6,
   4
  ],
  [
   6,
   4,
   7
  ],
  [
   2,
   5,
   2
  ],
  [
   1,
   6,
   5
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "cut_value": 50,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example infra_fault_domain_split --format json | hexstellar solve maxcut
curl -s https://api.hexstellar.com/api/v1/examples/infra_fault_domain_split        # the full example over HTTP

📡 Redundant Probe Placement

Infrastructure · command cover · effort flash · id: infra_probe_placement

Booleans are the probes, not the links; redundancy is a per-element floor under a ceiling, so surplus cover is forbidden, not priced.

Five network links need monitoring. Two of them are critical and must be watched by two independent probes; the rest need one. No link may carry more than two probes, because a third adds measurement interference rather than confidence. Six probe placements are available, and two of them run on the same host, so they cannot both be deployed. HexStellar returns the cheapest deployment that satisfies the floors, the ceiling and the conflict at once: probes 0, 1, 2 and 3, cost 10. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer lists the deployed probe indices. uncovered counts links below their floor; violations counts links above the ceiling plus any broken conflict. A valid deployment has both at 0.

Where this shows up

Network and service monitoring with redundancy targets, dual-sensor safety instrumentation, seismic and environmental station siting, quorum witness placement, camera coverage where overlapping views waste storage — anywhere redundancy has both a minimum and a maximum.

The same encoding also solves 7

  • Safety-instrumented transmitter siting where SIL-rated process variables need two independent measurementsIndustrial Automation
    sets → installable tap points and the process variables each transmitter reads, elements → the process variables, min_cover → 2 on SIL-rated variables and 1 on the rest, max_cover → 2 taps per variable because each extra tap is another process penetration, cost → installed price of the tap and its I/O, conflicts → two taps that need the same spare channel on one I/O card
  • PMU siting so every bus is observable and tie buses carry two independent observationsElectric Utilities
    sets → candidate PMU sites and the buses each site's channels observe, elements → buses in the network model, min_cover → 2 on tie buses and 1 elsewhere, max_cover → 2 observations per bus so surplus channels are not bought, cost → hardware plus commissioning per site, conflicts → two sites that would share one substation's single communications port
  • In-line metrology sampling so every process layer is measured and critical litho layers measured twiceSemiconductors
    sets → metrology recipes and the process layers each one measures, elements → layers in the flow, min_cover → 2 on critical litho layers and 1 on the rest, max_cover → 2 sampling plans per layer, the ceiling the MES will schedule, cost → per-wafer measurement charge for the recipe, conflicts → two recipes that would need the same tool in two incompatible hardware configurations, so only one of them can be qualified on it
  • Camera position selection where officiating zones need two angles and no zone gets more than two feedsBroadcast Media
    sets → rigged camera positions and the venue zones each covers, elements → zones of the venue, min_cover → 2 on officiating zones and 1 elsewhere, max_cover → 2 feeds per zone so the replay bank is not filled with duplicates, cost → rig plus operator price per position, conflicts → two positions that would need the same crane
  • Surface-surveillance sensor siting so every taxiway segment is seen and runway crossings seen twiceAviation
    sets → candidate sensor masts and the movement-area segments each one detects on its own (an independent detector per mast, not one receiver of a multi-receiver position fix), elements → taxiway segments and runway crossings, min_cover → 2 at runway crossings and 1 on the rest, max_cover → 2 masts per segment, the ceiling the surveillance fusion accepts before one aircraft starts splitting into two tracks, cost → mast, civil works and power drop per site, conflicts → two masts that would stand in the same obstacle-clearance envelope, where only one may be built
  • Market-data capture appliance placement with two independent captures on best-execution venuesCapital Markets
    sets → capture appliances and the venue feeds each one can tap, elements → venue feeds to be recorded, min_cover → 2 on venues used for best-execution evidence and 1 elsewhere, max_cover → 2 captures per feed, enough for the two records to be compared without paying for a third appliance, cost → appliance plus cross-connect price, conflicts → two appliances that require the same cage cross-connect port
  • Election observer route assignment where contested precincts need two independent observersElection Administration
    sets → observer routes, one row per accredited observer's itinerary, and the precincts each route reaches, elements → precincts to be observed, min_cover → 2 in contested precincts and 1 elsewhere, max_cover → 2 observers per precinct so no polling place is crowded, cost → travel plus stipend for the route, conflicts → any two routes only the same accredited observer could work, which is what makes two covers two different people

Measured at scale actually run

At 4,000 candidate probe placements over 12,000 monitored links — 40,433 (placement, link) incidences submitted as one 261 KB request — this encoding returned a deployment labelled heuristic rather than certified, so its cost and its uncovered and violations counts are a hypothesis to re-check with the free verify call.

Instance
12,000 elements · 4,000 sets · 40,408 incidences
Answer
heuristic (labelled)
Engine time
872 ms (826 ms–876 ms, n=3)
Peak memory
16.7 MB
Request
261 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only cover --sizes target

How the encoding grows

At 4,000 candidate placements over 25,000 monitored elements the identical encoding is 4,000 booleans, 4,000 covered-element lists (about 24,000 (candidate, element) incidences at six elements each), a 25,000-entry min_cover array of floors, a 25,000-entry max_cover array of ceilings, a 4,000-entry cost array and one [a,b] row per mutually exclusive pair — one request, the same six fields as the five-element version. Certainty is labelled on every answer and certification is proven by exhaustion, so an instance that size comes back marked heuristic instead of claiming an optimum it did not prove.

The encoding recipe (agent notes)

FLOORS AND CEILINGS ARE DIFFERENT PARAMETERS, AND REAL PROBLEMS HAVE BOTH. min_cover accepts an ARRAY so each element carries its own floor (2 for the critical links, 1 for the rest); max_cover is the ceiling, and a ceiling at or above the number of candidates covering an element is ignored as vacuous. conflicts takes [a,b] pairs of CANDIDATES that cannot coexist — resource collisions, not coverage. COMMON MISTAKES: (1) modeling the ceiling as a cost penalty — over-coverage then becomes merely expensive instead of forbidden, and the engine will happily buy it when coverage is scarce; (2) putting the conflict on the ELEMENTS instead of the probe pair — conflicts live between candidates, exactly like the exclusions in the maneuver and gallery examples; (3) a floor above its ceiling, or a conflict between two forced probes, is refused at the door with the offending element named — read that as your model contradicting itself, not as a solver limit; (4) if the ceiling is really 'at most k of THESE specific probes' rather than per link, that is rules capacity_limit — this ceiling counts covers of an element. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Deploy the cheapest set of probes so critical links get two independent probes, every link gets at least one, no link exceeds two, and two same-host probes are never both deployed.",
 "sets": [
  [
   0,
   1
  ],
  [
   1,
   2
  ],
  [
   2,
   3
  ],
  [
   3,
   4
  ],
  [
   0,
   4
  ],
  [
   1,
   3
  ]
 ],
 "min_cover": [
  1,
  2,
  1,
  2,
  1
 ],
 "max_cover": 2,
 "cost": [
  3,
  2,
  3,
  2,
  3,
  4
 ],
 "conflicts": [
  [
   0,
   4
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "total_cost": 10,
 "uncovered": 0,
 "violations": 0,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example infra_probe_placement --format json | hexstellar solve cover
curl -s https://api.hexstellar.com/api/v1/examples/infra_probe_placement        # the full example over HTTP

🗄️ Workload Placement Across Hosts

Infrastructure · command rules · effort flash · id: infra_workload_placement

A multi-way choice is one boolean per item-slot pair plus choose_one; keep-apart is one exclusion per slot, never one rule between items.

Four services (A, B, C, D) must each land on exactly one of three hosts. No host may run more than two services. A and B are a redundant pair, so for resilience they must sit on different hosts — the same for C and D. HexStellar returns a placement with zero rule violations, or tells you how many rules could not be satisfied at once. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is a 0/1 flag per decision variable in a one-hot layout: variable (service*3 + host) is 1 when that service runs on that host. violations is 0 when every rule holds — the placement is valid.

Where this shows up

Datacenter scheduling, container/pod placement, replica anti-affinity, high-availability spread across racks or zones.

The same encoding also solves 7

  • Berthing ambulances in station garages so the two units covering one district never share a garagePublic safety
    services → ambulances, hosts → station garages, choose_one per service → each unit is berthed in exactly one garage, capacity_limit k per host → the bays in that garage, mutual_exclusion per host on a pair → the two units covering the same district, which must not be lost to one garage incident
  • Distributing a collection across storage vaults so the only two copies of a work are never in one roomCultural heritage
    services → objects, hosts → storage vaults, choose_one → each object is stored in exactly one vault, capacity_limit k → the vault's shelf positions, mutual_exclusion per vault → the preservation master and its only duplicate copy, which the storage policy keeps in different rooms so one fire or flood cannot take both
  • Distributing key shares to custodians so no custodian can reach the reconstruction threshold aloneCryptography
    services → key shares, hosts → custodians, choose_one → each share is held by exactly one custodian, capacity_limit k = t-1 → the rule that no custodian holds the t shares needed to reconstruct, mutual_exclusion per custodian → two shares of one quorum-critical pair that must never sit together
  • Seating exam candidates in rooms under a collusion screenEducation
    services → candidates, hosts → exam rooms, choose_one → each candidate sits in exactly one room, capacity_limit k → the room's invigilated seat count, mutual_exclusion per room → a pair flagged for prior collusion who must not sit in the same room
  • Assigning inpatients to ward bays under infection-control separationHealthcare
    services → patients awaiting a bed, hosts → ward bays, choose_one → each patient is placed in exactly one bay, capacity_limit k → the beds in that bay, mutual_exclusion per bay → a pair the infection-control rule keeps apart (a colonised patient and an immunosuppressed one)
  • Splitting custodians across document-review teams so an ethical wall is never crossedLegal
    services → each custodian's document set, hosts → review teams, choose_one → each set is reviewed by exactly one team, capacity_limit k → the sets a team can take, mutual_exclusion per team → two custodians on opposite sides of the ethical wall, who must not be read by one team
  • Placing duplicate seed accessions in gene banks so one bank's failure never loses a landraceAgriculture
    services → physical seed samples, hosts → gene banks, choose_one → each sample is stored at exactly one bank, capacity_limit k → that bank's cold-store positions, mutual_exclusion per bank → the two duplicate samples of one landrace, which must be kept in different banks

Measured at scale actually run

Measured at 100,000 service-on-host variables under 30,000 declared capacity and keep-apart rules in one 1,602 KB request, the same encoding placed every service at once and returned a rule-violation count that is certified minimal and independently checked, not a plausible arrangement handed over without a label.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape at 400 items across 60 slots is 400x60 = 24,000 binary variables, 400 choose_one groups, 60 capacity_limit rules, and one mutual_exclusion per slot per protected pair, so 150 protected pairs add 150x60 = 9,000 exclusions and 9,460 rules travel in one request. Only the counts grow, not the rule types; items x slots must stay within the declared ceiling of 100,000 variables, which a single request has carried in full, and violations is reported per answer, where zero certifies every declared rule holds and a positive count states how many could not hold at once.

The encoding recipe (agent notes)

ENCODING A MULTI-WAY CHOICE AS BOOLEANS: rules decides yes/no per variable, so to place a service on one of H hosts, give it H variables (service*H + host) and add choose_one over them — exactly one is picked. Bound each host with capacity_limit (k = max per host) over that host's variables. 'A and B not co-located' becomes, for each host h, mutual_exclusion over [A_h, B_h] (they can't both be 1 on the same host). COMMON MISTAKES: (1) forgetting choose_one, which lets a service be placed on zero or many hosts; (2) writing one different on the service indices — services aren't single variables here, they're groups, so anti-affinity is per-host mutual_exclusion, not one different; (3) node indices out of range — with 4 services × 3 hosts, n must be 12 and indices run 0..11. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Place every service on a host, respect capacity, and keep each redundant pair apart.",
 "n": 12,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1,
    2
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    3,
    4,
    5
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    6,
    7,
    8
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    9,
    10,
    11
   ]
  },
  {
   "type": "capacity_limit",
   "k": 2,
   "nodes": [
    0,
    3,
    6,
    9
   ]
  },
  {
   "type": "capacity_limit",
   "k": 2,
   "nodes": [
    1,
    4,
    7,
    10
   ]
  },
  {
   "type": "capacity_limit",
   "k": 2,
   "nodes": [
    2,
    5,
    8,
    11
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    3
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    1,
    4
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    2,
    5
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    6,
    9
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    7,
    10
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    8,
    11
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example infra_workload_placement --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/infra_workload_placement        # the full example over HTTP

◎ Residual-Guarded Fault Isolation

Infrastructure · command simulator · effort flash · id: simulator_fault_isolation

Two independently checked layers support one bounded claim; missing evidence would withhold it.

A policy layer and a fault-isolation layer run through their real product paths. Two typed criteria close, so one deliberately bounded claim is allowed. This is a transfer recipe: replace the domain, capabilities, bindings and external evidence without weakening the claim guard.

Reading the answer

Read claim_allowed first, then the typed residual, weakest_link and each layer receipt. A completed layer is not permission to make a claim whose required criterion is missing.

Where this shows up

Infrastructure, power systems, chemistry workflows, astronomy screening, chip design, research pipelines

The same encoding also solves 3

  • Power-grid islanding plus an upstream AC power-flow residualEnergy
    islanding → maxcut layer; operating rules → rules layer; measured MW/voltage residual → recorded oracle criteria
  • Active-region choice plus an external electronic-structure calculationQuantum chemistry
    candidate region → select layer; required states → cover layer; external energy/error receipt → oracle criteria
  • Orbital conjunction screening followed by a trusted propagatorSpace
    exclusions → rules layer; high-risk subset → select layer; propagated miss distance → recorded oracle criterion

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Evaluate a fault-isolation design with an independent policy check.",
 "intent": "separate all weighted dependencies while satisfying every declared placement rule",
 "catalog_size": 4,
 "budget": {
  "compute_units": 2,
  "wall_ms": 10000
 },
 "flow": {
  "mode": "single_pass"
 },
 "layers": [
  {
   "id": "policy",
   "capability": "rules",
   "units": 1,
   "payload": {
    "n": 4,
    "constraints": [
     {
      "type": "different",
      "nodes": [
       0,
       1
      ]
     },
     {
      "type": "different",
      "nodes": [
       1,
       2
      ]
     },
     {
      "type": "different",
      "nodes": [
       2,
       3
      ]
     }
    ]
   }
  },
  {
   "id": "isolation",
   "capability": "maxcut",
   "units": 1,
   "depends_on": [
    "policy"
   ],
   "payload": {
    "n": 4,
    "edges": [
     [
      0,
      1,
      1
     ],
     [
      1,
      2,
      1
     ],
     [
      2,
      3,
      1
     ],
     [
      3,
      0,
      1
     ]
    ]
   }
  }
 ],
 "criteria": [
  {
   "id": "policy_clean",
   "kind": "violations",
   "source": "layer:policy.violations",
   "relation": "at_most",
   "target": 0,
   "hard": true
  },
  {
   "id": "all_links_separated",
   "kind": "separated_weight",
   "source": "layer:isolation.cut_value",
   "relation": "at_least",
   "target": 4,
   "hard": true
  }
 ],
 "claims": [
  {
   "id": "bounded_design",
   "text": "The supplied four-node design meets the two declared criteria.",
   "requires": [
    "policy_clean",
    "all_links_separated"
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "status": "resolved",
 "claim_allowed": true,
 "weakest_link": "checked_composition",
 "certainty": "checked composition",
 "receipt": "31f724ea80ce"
}

Run it

terminal
hexstellar example simulator_fault_isolation --format json | hexstellar solve simulator
curl -s https://api.hexstellar.com/api/v1/examples/simulator_fault_isolation        # the full example over HTTP

Logistics

📦 Container Loading With Incompatible Goods

Logistics · command rules · effort flash · id: logistics_container_incompat

Items are groups of variables, not variables, so keep-apart is one mutual_exclusion per container, never a single rule between two items.

Four items must each be loaded into one of two containers, with no container holding more than three. Two pairs of items are incompatible (for example a cleaning chemical and a foodstuff) and must never share a container. HexStellar returns a loading plan with zero rule violations. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is one-hot per item: variable (item*2 + container) is 1 for the chosen container. violations is 0 when the capacity and separation rules all hold.

Where this shows up

Container and truck loading with segregation rules, hazmat separation, warehouse zoning, any 'these two can never sit together' packing.

The same encoding also solves 6

  • Placing tenant virtual machines on hypervisor hosts under anti-affinity policiesCloud infrastructure
    item → a virtual machine, container → a host, item-by-container variable → this VM runs on this host, choose_one → each VM lands on exactly one host, capacity_limit k → the host's VM slot count, mutual_exclusion on a pair's same-host variables → an anti-affinity rule between two VMs, violations → the number of placement rules broken
  • Loading unit load devices into aircraft holds under dangerous-goods segregationAir cargo
    item → a unit load device, container → an aircraft hold (the compartment, not a single position), variable → this ULD stowed in this hold, choose_one → each ULD in exactly one hold, capacity_limit k → the number of ULD positions inside that hold, mutual_exclusion on a pair's same-hold variables → two ULDs whose dangerous-goods classes may not share a hold, violations → the number of loading rules broken
  • Assigning client accounts to trading desks across an information barrierFinancial services
    item → a client account, container → a desk, variable → this account served by this desk, choose_one → each account served by exactly one desk, capacity_limit k → accounts a desk may carry, mutual_exclusion → two accounts on opposite sides of an information barrier sharing a desk, violations → the number of compliance rules broken
  • Allocating prisoners to wings under keep-apart ordersCorrections
    item → a prisoner, container → a wing, variable → this prisoner on this wing, choose_one → each prisoner on exactly one wing, capacity_limit k → beds on the wing, mutual_exclusion → a keep-apart pair sharing a wing, violations → the number of allocation rules broken
  • Scheduling product campaigns into shared bioreactor suites under cross-contamination rulesPharmaceutical manufacturing
    READ IT AS ALLOCATION FOR ONE PERIOD, NOT SEQUENCING: item → a product campaign in the period, container → a bioreactor suite, variable → this campaign runs in this suite, choose_one → each campaign in exactly one suite, capacity_limit k → campaigns the suite can host in the period, mutual_exclusion on a pair's same-suite variables → two products that may not share a suite in the period, violations → the number of segregation rules broken. Changeover ORDER inside a suite ('B may not run straight after A') is an adjacent-pair cost, not one of these rule types - take that to tsp.
  • Assigning inpatients to bays under infection-control separationHealthcare
    item → a patient, container → a bay, variable → this patient in this bay, choose_one → each patient in exactly one bay, capacity_limit k → beds in the bay, mutual_exclusion → a colonised patient and an immunocompromised patient sharing a bay, violations → the number of infection-control rules broken

Measured at scale actually run

The identical encoding carrying 100,000 (item, container) variables — 10,000 items across 10 containers — under 30,000 choose-one, capacity and per-container separation rules returns a loading plan whose violation count is certified as the minimum, the whole 1,602 KB request fitting inside 16,588 KB of peak memory.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape at 900 items and 40 containers is 900 x 40 = 36,000 binary variables and 3,340 rules in one request: 900 choose_one rules (one per item, over its 40 container variables), 40 capacity_limit rules, and one mutual_exclusion per container per forbidden pair (60 declared pairs x 40 containers = 2,400). Only the item-by-container product grows, not the rule types; violations is recounted rule by rule from the returned plan, so zero certifies that every separation and capacity rule holds at once.

The encoding recipe (agent notes)

'NEVER TOGETHER' AS A FEASIBILITY RULE: give each item one variable per container (item*C + container) and a choose_one so it lands in exactly one. Bound each container with capacity_limit. Two items that must be separated become, for each container, a mutual_exclusion on their same-container variables (they can't both be 1 in the same container). COMMON MISTAKES: (1) one different on the item indices — items are GROUPS of variables here, so separation is per-container mutual_exclusion, not a single different; (2) capacity so tight the separation can't be honored (e.g. both incompatible items forced into the only container with room) — the engine will report violations > 0, which is your signal to add capacity or a container; (3) index range — 4 items × 2 containers means n=8, indices 0..7. When you also want to REWARD tight packing (not just satisfy rules), move to optimize and add the fill reward as negative linear weights. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Load every item into a container, respect capacity, keep incompatible goods apart.",
 "n": 8,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    2,
    3
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    4,
    5
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    6,
    7
   ]
  },
  {
   "type": "capacity_limit",
   "k": 3,
   "nodes": [
    0,
    2,
    4,
    6
   ]
  },
  {
   "type": "capacity_limit",
   "k": 3,
   "nodes": [
    1,
    3,
    5,
    7
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    2
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    1,
    3
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    4,
    6
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    5,
    7
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example logistics_container_incompat --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/logistics_container_incompat        # the full example over HTTP

🏭 Cross-Dock Door Assignment

Logistics · command qap · effort flash · id: logistics_crossdock_hub

A bijection that prices closeness but cannot forbid it: one item per location; hard separations and shared locations move to rules.

At a cross-dock hub, every inbound stream must be assigned to a dock door. Pallets flow between streams, and each pair of doors is a physical distance apart. HexStellar assigns streams to doors so the total forklift travel — flow times distance, summed over every pair — is as small as possible. For this size the assignment is a certified optimum. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is a permutation: answer[i] is the door assigned to stream i. cost is the total flow×distance handling effort (lower is better).

Where this shows up

Cross-dock and warehouse door assignment, terminal berth planning, any 'put heavily-interacting things physically close' layout.

The same encoding also solves 11

  • Hospital department layout across a floor planHealthcare facilities
    flow → yearly patient and staff transfers between department i and department j, dist → walking distance between floor units a and b, answer[i] → the unit for department i, cost → total distance walked over the year
  • Gate assignment for one departure bank at an airportAviation
    flow → connecting passengers transferring between flight i and flight j, dist → walking distance between gates a and b, answer[i] → the gate for flight i; the bijection is honest inside one bank (n flights, n gates), while gates reused across overlapping banks need rules: one binary per (flight, gate), choose_one per flight so every flight takes exactly one gate, mutual_exclusion over time-overlapping flights at the same gate, and the same connecting-passenger x walking-distance products as quadratic terms
  • Slotting SKUs into pick faces by co-pick frequencyWarehousing
    flow → number of orders containing both SKU i and SKU j, dist → pick-path distance between faces a and b, answer[i] → the face for SKU i; the single-line trip from a face to the pack station is a per-location linear cost qap has no field for, so carry it in rules: one binary per (SKU, face), choose_one per SKU and per face, linear = pick frequency x distance to the pack station, quadratic = the same flow x distance products
  • Assigning reactive chemicals to storage bays that keep hazardous pairs apartIndustrial safety
    flow → reactivity hazard score for the chemical pair (i,j), dist → proximity of bays a and b ((widest separation − separation), so a hazardous pair costs most stored side by side), answer[i] → the bay for chemical i; this PRICES proximity, it does not forbid it — a hard segregation rule (these two may never occupy neighbouring bays) is not a qap field, so state it with rules: one binary per (chemical, bay), choose_one per chemical and per bay, mutual_exclusion over each forbidden (chemical i in bay a, chemical j in bay b) combination, quadratic = the same hazard x proximity products
  • Assigning broadcast channels to the transmitters of a regional radio networkTelecommunications spectrum planning
    flow → measured interference coupling between transmitter i and transmitter j (how strongly their coverage footprints overlap), dist → spectral closeness of channel a and channel b written as (widest spacing in the licensed band - |a - b|), so a coupled pair costs most when their channels sit next to each other, answer[i] → the channel assigned to transmitter i, cost → total interference exposure across the network. The permutation is honest when the licence grants exactly n channels for n transmitters; a channel re-used by several transmitters, or a transmitter frozen on its current licence, is not a qap field and comes from rules: one binary per (transmitter, channel), choose_one per transmitter, capacity_limit k = permitted re-uses per channel, force_true on the frozen (transmitter, channel) pair, quadratic = the same coupling x closeness products.
  • Slotting component reels into the feeder bank of a pick-and-place machineElectronics manufacturing
    flow → the number of times the fixed placement program picks part i immediately before or after part j over one board, dist → head travel distance between feeder slot a and feeder slot b, answer[i] → the feeder slot holding reel i, cost → total head travel per board, which is the machine's cycle-time driver. One reel per slot is the honest reading for equal-width reels; a part restricted to a tray position, a reel pinned to its current slot to avoid a changeover, and a wide reel that spans two adjacent slots are capacity and pinning facts qap has no field for, so state them with rules: one binary per (reel, slot), choose_one per reel, capacity_limit k=1 per slot, force_false for every disallowed (reel, slot), force_true for a pinned reel, and for a double-width reel index its binaries by (reel, starting slot) with mutual_exclusion over every pair of placements whose two-slot footprints overlap; quadratic = the same pick-adjacency x travel products.
  • Assigning scenes to the days of a shooting schedule so cast standby is minimizedFilm and television production
    flow → the number of cast members that scene i and scene j share, dist → the number of calendar days between shooting day a and shooting day b, answer[i] → the day scene i is shot, cost → the shared-cast-weighted spread of the schedule: every shared actor is charged for each day separating a pair of their scenes, so the objective is the standby pressure that drives hold-day billing, not the payroll total itself. One scene per day keeps the permutation honest; a day that holds several scenes, an actor's contracted availability window, or a location that must be shot on consecutive days are not qap fields and come from rules: one binary per (scene, day), choose_one per scene, capacity_limit k = scenes per day, force_false for days outside an availability window, requires to bind a location's second scene to the day after its first, quadratic = the same shared-cast x day-gap products.
  • Placing acts into the stage-and-time slots of a two-stage festival dayLive events programming
    flow → the size of the audience shared by act i and act j, taken from ticket or streaming history, dist → the minutes that slot a and slot b overlap (zero for two slots on the same stage, which cannot clash), answer[i] → the slot given to act i, cost → total fan-minutes of forced choice across the day. The permutation fits when the day has exactly as many slots as booked acts; a contracted headline slot, an act's travel window, or a stage that must stay dark during the main set are not qap fields and come from rules: one binary per (act, slot), choose_one per act and per slot, force_true for the contracted headline pairing, force_false for slots outside an act's travel window, quadratic = the same shared-audience x overlap-minutes products.
  • Placing avionics boxes on the equipment panel of a satellite busSpacecraft integration
    flow → the number of harness conductors running between box i and box j, dist → the routed cable-run length between mounting position a and mounting position b, answer[i] → the mounting position for box i, cost → total conductor length, which converts directly into harness mass on the launch budget. The permutation holds when there are as many qualified positions as boxes; thermal and viewing rules (a dissipating box must sit on the radiator panel, a star tracker must keep its aperture clear, a position reserved for the propulsion feed) are not qap fields and come from rules: one binary per (box, position), choose_one per box and per position, force_false for every disallowed (box, position), force_true for a position already frozen by the mechanical baseline, quadratic = the same conductor-count x run-length products.
  • Redistributing specialist companies across a city's firehousesEmergency services deployment
    flow → the number of incidents in the last year that dispatched company i and company j to the same scene, dist → road drive time between firehouse a and firehouse b, answer[i] → the firehouse that company i is stationed in, cost → co-dispatch-weighted road separation across the deployment: each pair of companies is charged its house-to-house drive time for every incident that called them both, which is the spread that sets the second-due arrival gap and the move-up cost, so habitual partners end up close on the road network. One company per house is honest when the city has n houses and n specialist companies; apparatus bay counts, a company that cannot leave its current house under a union agreement, and a house whose bay is too short for the ladder truck are not qap fields and come from rules: one binary per (company, house), choose_one per company, capacity_limit k = usable bays per house, force_true to hold a company in place, force_false for every (company, house) the apparatus does not physically fit, quadratic = the same co-response x drive-time products.
  • Seating orchestra sections on the risers of a concert platformPerforming arts
    flow → the number of passages across the programme where section i and section j must enter together or hand a line back and forth, counted from the scores, dist → the metres between riser a and riser b, which is the sound delay each pair has to play through, answer[i] → the riser given to section i, cost → total delay-weighted coupling the players must compensate for. The permutation fits a platform built with one riser per section; the conductor's fixed placements (percussion on the back riser, first violins to the conductor's left) and a riser that cannot carry the harp are not qap fields and come from rules: one binary per (section, riser), choose_one per section and per riser, force_true for each fixed placement, force_false for a riser that cannot take a section's weight or footprint, quadratic = the same passage-count x separation products.

Measured at scale actually run

A 200-stream, 200-door hub packs 40,000 pallet-flow entries and 40,000 door-to-door distances into a 294 KB request and gets one door back for every inbound stream, marked heuristic rather than a certified optimum - so the forklift-travel total stays a hypothesis until the free verify call re-adds it.

Instance
200 variables · 40,000 flow entries · 40,000 distance entries
Answer
heuristic (labelled)
Engine time
26 ms (26 ms–26 ms, n=3)
Peak memory
3.0 MB
Request
294 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only qap --sizes target

How the encoding grows

A 90-door hub is the same request with two 90x90 matrices: 16,200 numbers, 4,005 unordered pairs on each side, and 8,010 flow-by-distance products in the objective, over one assignment out of 90! possible ones. Nothing about the encoding changes with n except the size of the two matrices, and each answer states its own certainty — certified below the exhaustion cap, explicitly heuristic above it.

The encoding recipe (agent notes)

THIS IS THE QUADRATIC ASSIGNMENT PROBLEM (QAP). Give it two square matrices of the same size: flow[i][j] = how much moves between item i and item j, and dist[a][b] = the physical distance between location a and location b. QAP finds the assignment of items→locations that minimizes Σ flow[i][j]·dist[assigned(i)][assigned(j)]. COMMON MISTAKES: (1) swapping the two matrices — flow is over ITEMS (streams), dist is over LOCATIONS (doors); they must be the same dimension but they mean different things; (2) expecting answer to be an on/off vector — for qap it's a PERMUTATION (each location used once); (3) asymmetric or self-loop entries — keep the diagonal 0 and the matrices symmetric unless the cost really is directional. This same shape models microservice placement (flow=RPC calls, dist=network latency) and chip floorplanning (flow=wires, dist=Manhattan distance) — one command, many industries. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Assign inbound streams to dock doors so forklifts travel the least.",
 "flow": [
  [
   0,
   40,
   10,
   5
  ],
  [
   40,
   0,
   25,
   8
  ],
  [
   10,
   25,
   0,
   30
  ],
  [
   5,
   8,
   30,
   0
  ]
 ],
 "dist": [
  [
   0,
   15,
   30,
   20
  ],
  [
   15,
   0,
   12,
   25
  ],
  [
   30,
   12,
   0,
   10
  ],
  [
   20,
   25,
   10,
   0
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "cost": 3480,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example logistics_crossdock_hub --format json | hexstellar solve qap
curl -s https://api.hexstellar.com/api/v1/examples/logistics_crossdock_hub        # the full example over HTTP

🚚 Last-Mile Delivery Route

Logistics · command tsp · effort flash · id: logistics_last_mile

Only length is the answer's real unit - reverse or rotate the order and it's the same optimum; a zero-cost dummy stop opens the loop.

A courier leaves the depot (0) and must deliver to seven addresses, then return. The matrix is the driving distance (km) between every pair. HexStellar returns the visiting order that minimizes the total distance — the classic Travelling Salesman Problem behind every route planner. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is the order to visit the stops; length is the total distance driven.

Where this shows up

Parcel and food delivery, field-service dispatch, drone survey paths.

The same encoding also solves 7

  • Ordering a night's observing target list so total telescope slew between consecutive pointings is leastAstronomy
    matrix[i][j] → the great-circle slew angle between target i and target j in arcseconds (integers, so scale before sending), answer → the order the targets are observed, length → the total slew angle around the closed list. Airmass and visibility windows are not expressible here: filter the list to one window first, then sequence what remains
  • Sequencing the drill hits of a printed-circuit-board panel so total head travel is leastElectronics manufacturing
    matrix[i][j] → the head travel between hole i and hole j in micrometres, answer → the drilling order, length → the total non-productive travel of the run. A tool change would have to be priced in the same units as travel, so group holes by tool diameter, sequence each group, and concatenate
  • Ordering the locations a shooting unit visits in one production day so total unit-move distance is leastFilm and TV production
    matrix[i][j] → the unit-move distance between location i and location j, answer → the order the locations are shot, length → the total move distance of the day. Cast availability and daylight windows are not in this encoding: assign scenes to days with rules first, then sequence each day here
  • Ordering a batch of queued disk reads so total head travel across cylinders is leastStorage systems
    matrix[i][j] → |cylinder(i) - cylinder(j)|, answer → the service order of the queued reads, length → the total head travel. The sequence closes back on itself; for a strictly open pass add one dummy request with cost 0 to every other, which makes the closing edge free and leaves the remaining order as the open path
  • Ordering the closed contours a laser cutter or 3D printer traverses so total rapid travel between them is leastAdditive manufacturing
    matrix[i][j] → the rapid-move distance between the fixed pierce point of contour i and that of contour j, answer → the order the contours are run, length → the total non-productive travel of the layer
  • Ordering the orbital targets a servicing spacecraft visits so total delta-v is leastSpace systems
    matrix[i][j] → the transfer delta-v between orbit i and orbit j in m/s rounded to integers, answer → the visit order, length → the mission's total delta-v. This holds only where transfer cost is taken as phase-independent; a cost that depends on a launch or phasing window is not expressible in a fixed matrix
  • Ordering the sampling plots a soil crew covers in one field pass so total machine travel including headland turns is leastAgriculture
    matrix[i][j] → the in-field travel between plot i and plot j including the headland turn, answer → the plot visiting order, length → the total travel of the pass

Measured at scale actually run

A 600-stop round for the same courier is one 600x600 driving-distance matrix of 360,000 entries submitted as a 2,054 KB request, and the visiting order comes back labelled heuristic - a hypothesis, not a proven shortest route - so recompute its 600 edge look-ups with the free verify call before the van is dispatched.

Instance
600 variables · 360,000 matrix entries
Answer
heuristic (labelled)
Engine time
103 ms (102 ms–110 ms, n=3)
Peak memory
11.6 MB
Request
2,054 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only tsp --sizes target

How the encoding grows

The identical shape at 200 stops is one 200x200 integer matrix - 40,000 entries holding 19,900 distinct pairwise costs - and the answer is one order of 200 indices whose length is the sum of 200 look-ups around the closed sequence. The count of distinct closed orders over 200 items is 199!/2, so only the matrix grows, not the structure; the certainty label marks the order as proven by exhaustion or as a labelled heuristic you recheck with those same 200 look-ups.

The encoding recipe (agent notes)

THE ENCODING RECIPE: tsp takes one full symmetric cost matrix — entry [i][j] is the cost of going from stop i to stop j — and returns the visiting order with the minimum total, returning to the start. COMMON MISTAKES: (1) an incomplete or inconsistent matrix — every pair needs a cost, in the same units; (2) storing or asserting the tour itself — a tour reversed or rotated is the SAME optimum, so the invariant is length, not the order; (3) thinking 'distance' means kilometers — the matrix can hold ANY transition cost: setup minutes between jobs, paint changeover cost (see the paint-shop example), tool-swap time, context-switch cost — tsp is a general sequencer of tasks with adjacency costs; (4) tsp holds NO time windows, capacities, or multiple vehicles — if the story needs those, decompose (cluster first, sequence within clusters) or model the constraints in rules/optimize instead of pretending the tour respects them. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "The shortest route for a courier who must visit every stop once and return.",
 "matrix": [
  [
   0,
   29,
   20,
   21,
   16,
   31,
   26,
   24
  ],
  [
   29,
   0,
   15,
   29,
   28,
   40,
   33,
   20
  ],
  [
   20,
   15,
   0,
   15,
   14,
   25,
   20,
   18
  ],
  [
   21,
   29,
   15,
   0,
   4,
   12,
   9,
   22
  ],
  [
   16,
   28,
   14,
   4,
   0,
   16,
   12,
   20
  ],
  [
   31,
   40,
   25,
   12,
   16,
   0,
   8,
   30
  ],
  [
   26,
   33,
   20,
   9,
   12,
   8,
   0,
   25
  ],
  [
   24,
   20,
   18,
   22,
   20,
   30,
   25,
   0
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "answer": [
  0,
  4,
  3,
  5,
  6,
  2,
  1,
  7
 ],
 "length": 119,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example logistics_last_mile --format json | hexstellar solve tsp
curl -s https://api.hexstellar.com/api/v1/examples/logistics_last_mile        # the full example over HTTP

🌐 Geopolitical Multi-Sourcing Rules

Logistics · command rules · effort flash · id: supply_bom_sourcing

An if/then contract clause is one implication between two (item, option) variables; choose_one is all that stops zero or several picks.

A hardware bill of materials must pick one supplier region per component, under supply-chain-risk rules: sourcing the microcontroller from one region forces the radar to come from another (diversification), and each component is sourced from exactly one region. HexStellar returns a sourcing plan that satisfies every dependency — here with zero violations. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is one-hot per component: variable (component*2 + region) is 1 for the chosen region. violations is 0 when every choose-one and dependency rule holds.

Where this shows up

Multi-sourcing and supplier diversification, dual-sourcing mandates, tariff/sanctions compliance, contractual 'if A then B' sourcing clauses.

The same encoding also solves 6

  • Placing reinsurance layers with carriers where taking one carrier on a layer obliges a different carrier on the layer aboveInsurance
    component → a risk layer, option → one approved placement panel for that layer (its carriers and their signed shares priced as a single package - the share arithmetic is done when the panels are built, because these rule types state no continuous quantity), variable → this layer placed on this panel, choose_one → exactly one panel per layer, requires [a,b] → layer 1 on panel A implies layer 2 on panel B, force_true → a panel already bound by the lead carrier, violations → the number of placement clauses broken
  • Vehicle build configuration where selecting the towing package obliges the heavy-duty alternator variantAutomotive
    component → an option group, option → a variant inside that group, variable → this group built as this variant, choose_one → exactly one variant per group, requires → the towing variant implies the heavy-duty alternator variant, force_true → the engine the dealer already ordered, violations → the number of configuration rules broken
  • Choosing a hosting jurisdiction per service where placing the data store in one jurisdiction obliges the audit-log service into the matching oneData residency
    component → a service, option → a jurisdiction, variable → this service hosted in this jurisdiction, choose_one → exactly one jurisdiction per service, requires → data store in jurisdiction J implies the audit-log service in J, force_true → a jurisdiction pinned by an existing contract, violations → the number of residency clauses broken
  • Assigning a fuel contract type per generating unit where taking spot supply at one plant obliges a fixed-price contract at its paired plantEnergy
    component → a generating unit, option → a contract type, variable → this unit on this contract type, choose_one → exactly one contract type per unit, requires → spot supply at unit 1 implies fixed-price at unit 2, force_true → a take-or-pay contract already signed, violations → the number of procurement-policy clauses broken
  • Assigning a release window per territory where licensing a title to one platform obliges a holdback window in the paired territoryMedia rights
    component → a territory, option → one pre-enumerated (platform, release window) bundle for that territory - the dates and holdback lengths are computed when the bundles are built, because these rule types state no date arithmetic, variable → this territory sold on this bundle, choose_one → exactly one bundle per territory, requires → bundle P in territory T implies the holdback bundle in the paired territory, force_true → the home-market bundle already sold, violations → the number of rights clauses broken
  • Booking each trade to a legal entity where booking a swap to the EU entity obliges an EU-authorised clearing routeBanking
    EACH TRADE NEEDS A SECOND OPTION FAMILY, NOT ONE: component → (a) the trade's booking-entity decision and (b) the same trade's clearing-route decision, option → a legal entity in family (a), a clearing route in family (b), variable → this trade takes this entity / this trade takes this route, choose_one → one rule per family, so exactly one entity AND exactly one route per trade, requires → the EU-entity variable implies the EU-authorised-route variable, force_true → an entity fixed by an existing master agreement, violations → the number of booking-model rules broken

Measured at scale actually run

Scaled to 100,000 (component, option) variables — 10,000 components with 10 approved regions each — under 30,000 choose-one rules and contractual if/then clauses, the sourcing plan arrives with a certified minimum violation count, from one 1,602 KB request rather than a per-clause loop.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape at 1,200 components with 12 approved options each is 14,400 binary variables and 1,200 choose_one rules, one per component over its 12 option variables. Every contractual if/then clause is exactly one requires over two (component, option) variables, so 3,000 clauses bring the request to 4,200 rules plus one force_true per decision already committed; violations is recomputed clause by clause from the returned plan, and zero certifies that all of them hold together.

The encoding recipe (agent notes)

requires MODELS A SOURCING DEPENDENCY: 'if the microcontroller is sourced from region X, the radar must come from region Y' is requires [mc_regionX, radar_regionY]. 'Each component from exactly one region' is choose_one over its per-region variables. A region already committed is force_true. COMMON MISTAKES: (1) getting the requires direction backwards — [mc_taiwan, radar_europe] means Taiwan-microcontroller ⇒ European-radar, not the reverse; (2) forgetting choose_one, which lets a component be sourced from zero or several regions; (3) trying to express 'at least 3 suppliers must be European' — that at-least-k rule is not a current type; use optimize for a minimum-count target. THE POINT: a procurement contract's 'if/then' clauses ARE logic constraints — the same requires+choose_one shape that rosters a hospital sources a supply chain. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Pick a supplier region per component so the sourcing-risk rules all hold.",
 "n": 6,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    2,
    3
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    4,
    5
   ]
  },
  {
   "type": "requires",
   "nodes": [
    0,
    3
   ]
  },
  {
   "type": "requires",
   "nodes": [
    2,
    5
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    0
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example supply_bom_sourcing --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/supply_bom_sourcing        # the full example over HTTP

Manufacturing

🧰 Assembly Kit Exact Partition

Manufacturing · command rules · effort flash · id: assembly_kit_partition

Inverted encoding: the booleans are the kits, one exactly-once rule lives on every part — the rules sit on the universe, not on the sets.

A lean assembly line needs parts P1-P4 and can pull from five pre-packed kits: {P1,P2}, {P2,P3}, {P3,P4}, {P1,P4}, and an all-in-one {P1,P2,P3,P4}. The rule is exact: every part must arrive in exactly one selected kit — a missing part stops the line, a duplicated part is dead stock. HexStellar returns a selection where the coverage works out perfectly (here kits {P1,P2} + {P3,P4}; kits {P2,P3} + {P1,P4}, or the all-in-one alone, are equally valid partitions). This is Exact Cover, one of Karp's original 21 NP-complete problems, expressed in four constraints. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is 1 when kit i is pulled. violations is 0 when every part appears in exactly one selected kit. Multiple exact partitions can exist — the invariant is the coverage, not which kits were picked.

Where this shows up

Kit-based assembly and spares provisioning, exact crew/pairing coverage (every flight leg on exactly one pairing), ticket bundling, tiling and pentomino puzzles (Sudoku is exact cover), auditing that a set of overlapping contracts covers every obligation exactly once — and multi-drug cocktail design: pick candidate drugs so every disease target/pathway is hit by exactly one mechanism, no gap and no needless toxicity overlap. The k=2 variant of the same shape ('every critical pathway covered by exactly TWO independent mechanisms') gives controlled-redundancy coverage.

The same encoding also solves 6

  • Crew pairing where every scheduled flight leg is flown by exactly one selected pairingAviation
    candidate set → a legal crew pairing (a chain of legs), element → a flight leg that must be flown, choose_exactly k=1 per element → that leg belongs to exactly one selected pairing, overlapping node lists → one leg appearing in many candidate pairings, violations → the number of legs left uncovered or covered twice
  • Redistricting where every precinct falls inside exactly one adopted districtGovernment
    candidate set → a proposed district (a bundle of precincts), element → a precinct, choose_exactly k=1 per precinct → the precinct sits in exactly one adopted district, choose_exactly k=N over ALL district variables → the map adopts exactly N districts, overlapping node lists → a precinct appearing in many proposed districts, violations → the number of precincts unassigned or claimed twice, plus the district-count rule if it is broken. Population balance is a weighted sum and contiguity is an adjacency property; neither is one of these rule types, so both must already hold of every candidate district before it is offered.
  • Ad inventory packaging where every sellable slot is sold inside exactly one packageAdvertising
    candidate set → a package offered to a buyer, element → an inventory slot, choose_exactly k=1 → each slot sold by exactly one accepted package, overlapping node lists → a slot quoted in several competing packages, violations → the number of slots unsold or oversold
  • Technology mapping where every node of a logic netlist is covered by exactly one library-cell matchSemiconductor design
    candidate set → one library-cell match and the connected subtree of netlist nodes it absorbs - split the netlist at fanout points into trees first, because on a tree a partition of the nodes automatically makes every chosen match's inputs the roots of other chosen matches, while on a general DAG it does not and 'this input is produced by one of several matches' is an at-least-one rule these types cannot state, element → a netlist node, choose_exactly k=1 → the node belongs to exactly one chosen match, overlapping node lists → matches competing for shared nodes, violations → the number of nodes unmapped or claimed twice
  • Polyomino tiling and Sudoku, where every cell is filled by exactly one placementPuzzles and games
    NARROW IT TO ONE NAMED PROBLEM - Sudoku, where every cell, row-digit, column-digit and box-digit requirement is met by exactly one placement: candidate set → one placement (digit d in row r, column c), element → one of the four requirement families (cell (r,c) is filled; digit d appears once in row r; digit d appears once in column c; digit d appears once in box b), choose_exactly k=1 per requirement → that requirement met exactly once, overlapping node lists → placements competing for the same cell, row, column or box, force_true → a given clue's placement, violations → the number of requirements unmet or met twice. Polyomino tiling is the same recipe with a piece-at-an-offset as the placement and a board cell as the element, and belongs in its own entry.
  • Cash application where every open invoice is cleared by exactly one remittance batchAccounting
    NARROW IT TO THE INVOICES AN ADVICE NAMES - cash application where every invoice named on the day's remittance advices is cleared by exactly one accepted application: candidate set → one candidate application (a remittance and the exact invoice set it clears; the amounts are balanced when the candidate is built, because these rule types state no sum), element → an invoice named on an advice, choose_exactly k=1 → that invoice cleared by exactly one accepted application, overlapping node lists → an invoice appearing in several candidate applications, violations → the number of named invoices unmatched or double-applied. Open invoices that no advice names are not elements and stay open.

Measured at scale actually run

At 100,000 candidate-kit booleans under 30,000 exactly-once coverage rules — one rule per required part, never one per kit — the returned selection's violation count is certified as the minimum, so a zero at that size is a proven exact partition: nothing short and nothing double-stocked.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape at 20,000 candidate sets covering 6,000 required elements is 20,000 binary variables and 6,000 choose_exactly k=1 rules — one per element, never one per set — whose node lists together carry one entry per (set, element) membership: at 8 elements per set that is 160,000 references in a single request. Raising k to 2 states doubled coverage without adding a variable, and violations is recounted element by element from the returned selection, so zero certifies a partition with no element short and none double-covered.

The encoding recipe (agent notes)

THIS IS EXACT COVER — and the encoding is inverted from what agents expect. The booleans are the SETS (kits), and each constraint is an ELEMENT: for every part, choose_exactly k=1 over the kits that contain it. The groups OVERLAP (kit 4 appears in all four constraints), and that overlap is the entire difficulty — picking the all-in-one kit satisfies every constraint at once, but picking it alongside anything else breaks all four. COMMON MISTAKES: (1) using capacity_limit (at most 1) instead of choose_exactly — that allows a part to be covered ZERO times, silently permitting shortages; exact cover needs exactly-one per element; (2) building one constraint per KIT instead of per PART — the constraints live on the universe being covered, not on the sets doing the covering; (3) the separability trap — kits look independent until you notice each part ties its kits together; never score kits individually; (4) when 'exactly once' is really 'at least once' (set cover, where overlap is acceptable), hard rules can't say at-least — flip the model: penalize overlap via optimize rewards, or keep exact cover and add a slack 'filler kit' per element if under-coverage is tolerable. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Pick kits so every required part is covered exactly once — no shortage, no double-stock.",
 "n": 5,
 "constraints": [
  {
   "type": "choose_exactly",
   "k": 1,
   "nodes": [
    0,
    3,
    4
   ]
  },
  {
   "type": "choose_exactly",
   "k": 1,
   "nodes": [
    0,
    1,
    4
   ]
  },
  {
   "type": "choose_exactly",
   "k": 1,
   "nodes": [
    1,
    2,
    4
   ]
  },
  {
   "type": "choose_exactly",
   "k": 1,
   "nodes": [
    2,
    3,
    4
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example assembly_kit_partition --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/assembly_kit_partition        # the full example over HTTP

🎨 Paint-Shop Batch Sequencing

Manufacturing · command tsp · effort flash · id: paint_shop_sequencing

Put 0 on every same-class pair and batching stops being a rule you enforce - the cost matrix is any changeover, not a distance.

On an automotive paint line, switching the color between two consecutive car bodies costs cleaning time and wasted solvent — and switching between some color pairs costs more than others. HexStellar orders the jobs so the total changeover cost around the run is as small as possible, batching same-color jobs and ordering the batches efficiently. For this size the sequence is a certified minimum. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is the order to run the jobs; length is the total changeover cost of that sequence (lower is better). Several sequences can tie at the minimum cost — any of them is a valid least-cost plan.

Where this shows up

Paint-shop and coating lines, injection-molding color runs, print-run plate changes, CNC tool-change sequencing, instruction/gate sequencing by transition cost (e.g., ordering circuit operations to minimize reconfiguration between neighbors), any 'order the work to minimize setup/changeover between steps' problem.

The same encoding also solves 7

  • Sequencing product campaigns on a shared tablet line so total cleaning-validation effort between consecutive products is leastPharmaceutical manufacturing
    matrix[i][j] → the cleaning requirement between product i and product j (0 inside one product family, a full strip when crossing a potency or allergen boundary), answer → the campaign order, length → the total cleaning effort of the run
  • Sequencing flavour runs on a filling line so the total product flushed at changeovers is leastFood and beverage
    matrix[i][j] → the litres flushed between run i and run j, 0 inside one flavour, answer → the run order, length → the total litres flushed. Allergen changeovers are direction-dependent and this matrix is symmetric: enter the heavier of the two directions and read length as an upper bound on the true directed cost
  • Ordering the segments of a studio rundown so total set, lighting and camera reconfiguration between consecutive segments is leastBroadcast media
    matrix[i][j] → the reconfiguration cost between segment i and segment j (0 when the two share one set and lighting state), answer → the running order, length → the total reconfiguration cost of the show
  • Ordering an operating room's elective case list so total instrument-tray and room turnover between consecutive cases is leastHealthcare
    matrix[i][j] → the turnover cost between case i and case j (0 when the two share one tray set and room configuration), answer → the case order, length → the total turnover cost of the list. Clinical priority and a case that must go first are orderings this encoding cannot state: split the list into priority tiers and sequence each tier on its own
  • Ordering coils in a hot-rolling campaign so total width-jump and grade-change cost between consecutive coils is leastSteel and metals
    matrix[i][j] → |width(i) - width(j)| plus the grade-change penalty for that pair, answer → the rolling order, length → the total campaign transition cost. A monotone width ramp is a hard ordering rule this encoding cannot state; it minimizes the jump cost rather than enforcing the ramp
  • Ordering a CI suite's test classes so total fixture teardown and rebuild between consecutive tests is leastSoftware delivery
    matrix[i][j] → the fixture cost of running test j straight after test i (0 when the two share one database or container fixture), answer → the execution order, length → the total fixture setup cost of the suite. A test with a required predecessor cannot be ordered by this encoding: collapse that group into one node with its internal order fixed
  • Ordering an LC-MS sample batch so total column re-equilibration between consecutive methods is leastAnalytical chemistry
    matrix[i][j] → the re-equilibration cost between the method of sample i and that of sample j (0 inside one method), answer → the injection order, length → the total re-equilibration cost of the batch

Measured at scale actually run

The same changeover encoding across 600 car bodies is a 600x600 cleaning-cost matrix of 360,000 entries in a 2,054 KB submission, and the run order arrives labelled heuristic rather than a certified minimum, so recompute its total changeover cost from those same 600 look-ups with the free verify call before the sequence is released to the line.

Instance
600 variables · 360,000 matrix entries
Answer
heuristic (labelled)
Engine time
103 ms (102 ms–110 ms, n=3)
Peak memory
11.6 MB
Request
2,054 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only tsp --sizes target

How the encoding grows

The identical shape at 120 bodies is a 120x120 integer matrix - 14,400 entries covering 7,140 distinct job pairs - but it is generated rather than typed: with 12 colors the whole matrix comes from a 12x12 changeover table, 66 distinct color-pair costs plus 0 on every same-color pair. The answer is one order of 120 job indices and length is the sum of 120 look-ups around the closed sequence, so only the matrix grows, not the structure; certification is reported per answer, and above the exact cap the order arrives labelled as a heuristic whose length you recompute from those same look-ups.

The encoding recipe (agent notes)

TSP IS NOT ONLY FOR MAPS — the 'distance' matrix is ANY pairwise transition cost. Here matrix[i][j] is the changeover cost of running job j right after job i: 0 when they share a color (no cleaning), and the color-pair cleaning cost otherwise. Minimizing the tour minimizes total changeover cost, which naturally BATCHES same-color jobs (a 0-cost run) and orders the batches to keep the between-color cost low. COMMON MISTAKES: (1) assuming TSP needs geographic coordinates — it only needs a cost matrix, and setup/changeover/switching cost is a perfect fit; (2) expecting a unique answer — when several sequences share the minimum cost, the engine returns one of them; the length is the invariant, not the exact order; (3) forgetting TSP closes the loop — the last job's changeover back to the first is counted; for a strictly open sequence at scale that one edge is negligible, or model it explicitly. THE UNLOCK: whenever your problem is 'put N tasks in an order that minimizes the cost of ADJACENT transitions' (setups, tool changes, warm-up, cleaning), it's a TSP in disguise. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Order the jobs so the paint line spends the least time cleaning between colors.",
 "matrix": [
  [
   0,
   2,
   6,
   9,
   6,
   9,
   2,
   0
  ],
  [
   2,
   0,
   4,
   7,
   4,
   7,
   0,
   2
  ],
  [
   6,
   4,
   0,
   3,
   0,
   3,
   4,
   6
  ],
  [
   9,
   7,
   3,
   0,
   3,
   0,
   7,
   9
  ],
  [
   6,
   4,
   0,
   3,
   0,
   3,
   4,
   6
  ],
  [
   9,
   7,
   3,
   0,
   3,
   0,
   7,
   9
  ],
  [
   2,
   0,
   4,
   7,
   4,
   7,
   0,
   2
  ],
  [
   0,
   2,
   6,
   9,
   6,
   9,
   2,
   0
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "length": 18,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example paint_shop_sequencing --format json | hexstellar solve tsp
curl -s https://api.hexstellar.com/api/v1/examples/paint_shop_sequencing        # the full example over HTTP

Music

🎼 Harmonic Modulation Planner

Music · command design · effort flash · id: music_key_modulation

Choose one of K cyclic values per slot with the anchors pinned — the cost wraps, so value 11 sits next to value 0.

A four-section piece — intro, bridge, climax, finale — needs one key per section, chosen from the 12 positions of the circle of fifths. Keys are genuinely CYCLIC: C is as close to F as to G, and the far side of the circle is the harshest possible jump. The intro and finale are anchored to the tonic, and the climax is pinned four fifths away for dramatic distance. The open question is the bridge: HexStellar returns [0, 2, 4, 0] — the bridge lands exactly halfway (two fifths up), splitting the journey into two smooth whole-steps around the circle rather than one wrenching leap, then the finale falls home. Certified optimal at every effort; brute force over all 20,736 assignments confirms it is the unique optimum (energy −18500). Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is the key (0..11, positions around the circle of fifths) chosen for section i. energy is the sum of the cyclic transition costs on each adjacent-section bond plus the anchor/climax biases — lower is smoother; here the certified minimum is −18500.

Where this shows up

Key and chord-progression planning, DJ set harmonic mixing (Camelot wheel), tasting-menu flavor-wheel sequencing, circadian dosing regimens (dose-timing profiles on a 24h wheel, avoiding jarring day-to-day shifts), shift-phase rotation planning, antenna phase steps, hue progression in generative art — any per-slot choice whose values live on a circle, where 'distance' wraps around. Periodic-boundary phase and unit-cell rotation assignment in lattice simulations is the same wrap-around structure.

The same encoding also solves 9

  • Torsion-angle (rotamer) assignment on a flexible moleculeComputational chemistry
    sections → rotatable bonds, keys → the K quantized torsion angles, bonds → sterically interacting bond pairs, circular j → ONE wrap-aware coupling shared by every interacting pair (357 degrees is 3 degrees from 0), bias → the per-site torsional profile, including a torsion pinned by a crystallographic restraint, energy → the total of that coarse coupled-torsion model at the returned angles. One j prices every pair identically; a model that needs a different energy surface per interacting pair is beyond a single shared coupling, and table does not help because it too is one shared KxK.
  • Interleaving the switching phases of a multiphase converterPower electronics
    sections → converter phases sharing one input rail, keys → the K clock-phase slots in the switching period, bonds → phase pairs drawing on the same capacitor, circular j<0 → a repulsive cyclic cost that spreads switching instants around the period, bias → the reference phase pinned to slot 0, energy → total ripple contribution
  • A colorway across a garment's panelsProduct design
    sections → panels, keys → the K hues of the colour wheel, bonds → adjacent panels, circular j<0 → the wrap-aware hue distance made repulsive, so adjacent panels contrast; j>0 instead pulls adjacent panels toward the SAME hue, a harmonious near-monochrome palette - it does NOT produce a gradient, because a stepped gradient asks each adjacent pair to differ by a fixed interval and circular builds a difference cost with no phase offset, bias → the brand hue pinned on the logo panel, energy → total adjacency cost of the palette.
  • Ground-state orientations of a K-state clock model with a pinned boundaryCondensed-matter physics
    sections → lattice sites, keys → the K allowed orientations, bonds → exchange-coupled neighbour pairs, circular j → the cyclic exchange coupling, j>0 aligning and j<0 opposing, bias → a boundary site pinned by an applied field, energy → the model's total energy at the returned orientation set
  • Setting the leg phases of a walking robot's gait cycleRobotics
    sections → the robot's legs, keys → the K sampled positions in one gait period, K even, so that half a period is itself an available value and position K-1 is one sample before position 0, bonds → the leg pairs that must strike out of step (the four perimeter pairs of a quadruped, leaving the diagonals unbonded), circular j<0 → ONE repulsive cyclic cost whose cheapest separation is exactly half a period, so every bonded pair alternates and the untouched diagonals land together, bias → the reference leg pinned to the touchdown sample the controller already fixed, energy → the total phase-mismatch score of the returned leg phases. A gait needing some pairs together and other pairs opposed at the same time is beyond one shared coupling: bond only the pairs that share the relation, and table does not help because it is likewise one shared KxK.
  • Rotation angle of every shading fin on a tower facadeArchitecture and facade engineering
    sections → the facade panels of the grid, keys → the K manufacturable fin rotations around the full turn (the last step is one step before zero), bonds → panel pairs sharing an edge, circular j>0 → ONE attractive cyclic cost that pulls neighbours toward nearly the same angle, so the elevation reads as broad continuous regions rather than visual noise, bias → the panels over the entrance and at the mechanical louvre pinned to the angles the daylight and airflow reviews require, energy → the total neighbour-mismatch score of the returned angle set. A facade specified as a fixed twist per floor is NOT this: a constant per-pair increment is a phase offset, and the coupling scores only the wrap-around difference between two panels.
  • Driving direction for the machine passes on each parcel of a farmPrecision agriculture
    sections → the parcels, keys → the K headings a machine can run, heading a meaning 180*a/K degrees (a worked line has no front, so heading K-1 is one step from heading 0 and the cost wraps), bonds → parcels that share a worked boundary, circular j>0 → ONE attractive cyclic cost that is cheapest when two neighbours run parallel and dearest when they meet square, which is exactly the overlap-and-turning penalty paid at a shared headland, bias → the parcel pinned to the contour heading its erosion plan requires, plus each parcel's own preference for running along its long axis, energy → the total heading cost of the returned field plan.
  • Which month each policy cohort renews in, across one underwriting bookInsurance operations
    sections → the policy cohorts, keys → the 12 renewal months (December is one step from January, so the cost wraps), bonds → cohort pairs handled by the same underwriting and claims team, circular j<0 → ONE repulsive cyclic cost that spreads a team's renewals around the year and prices a near-miss month as nearly as costly as the same month, because renewal work spills into the weeks either side, bias → the cohort pinned to the anniversary month its regulator fixes, energy → the total workload-collision score of the returned renewal calendar. A hard ceiling of the form 'no more than 40 renewals in any one month' is a capacity rule with no term here: declare it in rules and take the feasible calendar from there.
  • Angular phasing of the shaped charges along a perforating gun stringOil and gas well completion
    sections → the charge positions along the carrier, keys → the K firing angles available around the carrier's circumference (angle K-1 is one step from angle 0), bonds → charge pairs close enough along the string that their entry holes load the same arc of casing, circular j<0 → ONE repulsive cyclic cost, dearest when a bonded pair points the same way and cheapest when they point opposite, so the holes distribute around the pipe instead of stacking on one side, bias → the charges pinned to the azimuth the log says faces the productive interval, energy → the total casing-loading score of the returned phasing.

Measured at scale actually run

Two thousand sections choosing among 8 cyclic values, coupled by 16,000 section-pair bonds and anchored by 1,000 bias triples, is a 214 KB request that comes back with one key per section. That plan carries the heuristic label — a hypothesis, not a proven minimum — so recompute the wrapped transition cost across every bond with the free verify call before treating it as the smoothest routing available.

Instance
2,000 items · 8 values · 16,000 bonds · 1,000 bias terms
Answer
heuristic (labelled)
Engine time
3 ms (3 ms–3 ms, n=3)
Peak memory
2.8 MB
Request
214 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only design --sizes target

How the encoding grows

The identical shape at 64 slots and 12 cyclic values is L = 64, K = 12, one bond per coupled pair (63 for a chain), a SINGLE number j, and one bias triple per anchor — over K^L = 12^64 assignments. The KxK cost is built from j at the far end and never transmitted, so raising K from 12 to 360 one-degree steps adds nothing at all to the request while taking the assignment count to 360^64; a hand-written table would have grown to 129,600 numbers to say the same thing. Certification is by exhaustion and is reported per answer, and energy is recomputable by summing floor(-j*1000*cos(2*pi*delta/K)+0.5) over the bonds plus each chosen bias.

The encoding recipe (agent notes)

THIS EXERCISES design's CIRCULAR COUPLING — for values that wrap. Passing circular: {"j": 1} builds the KxK cosine cost automatically: same value is cheapest, opposite side of the circle is dearest, and the cost wraps — no hand-written table, no risk of encoding circular distance as linear distance. Anchors and dramatic pins are bias triples ([site, value, energy], negative = reward). COMMON MISTAKES: (1) modeling cyclic values with a LINEAR distance table — that makes key 11 maximally far from key 0 when they are actually neighbors on the circle; if the values wrap, the cost must wrap; (2) the separability trap — with only the anchors, each section optimizes alone; the BONDS between adjacent sections are what turn this into one coupled routing problem (the bridge's best key depends on both its neighbors); (3) expecting the engine to pick how many sections or their order — sites and bonds are the fixed skeleton; the engine chooses the VALUES; sequencing tasks by transition cost is tsp instead; (4) sign confusion — j positive makes equal values attract (smooth preference); negative makes adjacent sections repel (maximum contrast, e.g. alternating textures); pick the sign to match the aesthetic, and verify by recomputing the reported energy from the quantized cosine table (floor(−j·1000·cos(2π·Δ/K)+0.5)). CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Choose a key per section so every modulation moves smoothly around the circle of fifths.",
 "L": 4,
 "K": 12,
 "bonds": [
  [
   0,
   1
  ],
  [
   1,
   2
  ],
  [
   2,
   3
  ]
 ],
 "circular": {
  "j": 1
 },
 "bias": [
  [
   0,
   0,
   -5000
  ],
  [
   2,
   4,
   -8000
  ],
  [
   3,
   0,
   -5000
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "energy": -18500,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example music_key_modulation --format json | hexstellar solve design
curl -s https://api.hexstellar.com/api/v1/examples/music_key_modulation        # the full example over HTTP

Operations

🧭 Calibration Polarity Audit

Operations · command rules · effort flash · id: calibration_polarity_audit

Same-polarity and opposite-polarity claims form a signed graph — the minimum violations IS the number of irreducible contradictions.

Four instruments carry calibration claims from three technicians: instruments 0 and 1 must read OPPOSITE polarity, 1 and 2 opposite, and 2 and 0 opposite — plus 2 and 3 must read the SAME. The three 'opposite' claims form an odd cycle, and no assignment of two polarities can satisfy an odd cycle of oppositions: at least one claim must be wrong. HexStellar returns the best possible assignment and reports violations: 1 — and that number is not a failure code, it is the MEASUREMENT: the frustration index of the signed claim-graph, the count of claims that cannot be reconciled no matter what (an NP-hard quantity in general). The satisfiable identical chord rides along untouched. The audit's deliverable is the count itself: 0 means the claim set is consistent; k means exactly k claims must be re-examined. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is instrument i's assigned polarity (0/1). violations is the invariant: the MINIMUM number of polarity claims that cannot hold simultaneously — here exactly 1, because three pairwise 'must differ' claims form an odd cycle. Which claim gets broken can vary; the count cannot.

Where this shows up

Sensor and wiring polarity audits, gyroscope/magnetometer sign conventions, ledger sign-convention reconciliation, alliance/rivalry consistency in organizational data, spin-glass frustration in materials — any two-state system where 'same' and 'opposite' relations coexist and you need to KNOW how contradictory the evidence is, not just whether it is.

The same encoding also solves 9

  • Haplotype phasing from read evidence, where the broken-claim count is the frustration of the read graphGenomics
    instruments → variant sites, polarity 0/1 → which of the two chromosome copies a site's allele sits on, different → a read asserting two sites carry alleles on opposite copies, identical → a read asserting they sit on the same copy, violations → the number of PAIRWISE read assertions no phasing can satisfy (this is the frustration of the read graph, not the minimum-error-correction score: MEC counts corrected allele observations, and one correction can repair several pairwise assertions from a read spanning three or more sites, so the two counts differ)
  • Recovering binary labels from annotators who supplied only relative judgments of same or opposite classMachine learning data operations
    instruments → unlabelled items, polarity → the class assigned to an item, different → an annotator saying two items are in opposite classes, identical → saying they are in the same class, violations → the irreducible annotator disagreement, which is the count of judgments to send for adjudication
  • Trace-polarity reconciliation across overlapping seismic surveys before a mergeSeismic surveying
    instruments → surveys, polarity → the recording convention a survey is stored in, different → an overlap comparison asserting two surveys are stored inverted, identical → a comparison asserting they match, violations → the number of overlaps that cannot all hold, so the count of survey headers to re-examine
  • Multi-microphone polarity audit from measured pairwise correlation on a live rigAudio engineering
    instruments → microphone channels, polarity → each channel's flip state, different → a measurement asserting a pair is inverted, identical → a measurement asserting a pair is in agreement, violations → the number of channel measurements that contradict, so the lines to re-check physically
  • Splitting a rack's devices across the A and B power feeds when high-availability pairs must be split and a device must share a feed with the switch that manages itData centre electrical design
    instruments → the rack-mounted devices being powered, polarity 0/1 → whether a device's primary cord lands on the A feed or the B feed, different → a redundancy requirement that the two members of a high-availability pair draw from opposite feeds, identical → a requirement that a device and its out-of-band management switch draw from the same feed so losing one feed never leaves a live device unmanaged, violations → the number of written feed requirements that no A/B allocation satisfies at once, which is the count to renegotiate or answer with added circuits
  • Assigning a housing unit's residents to two wings when keep-separate orders and must-stay-together pairings collideCorrections
    instruments → the residents to be housed, polarity 0/1 → which of the two wings a resident is assigned to, different → a keep-separate order requiring two named residents to be in opposite wings, identical → a pairing that must stay in the same wing, such as a co-enrolled programme pair or an assigned medical buddy, violations → the number of standing orders that cannot all be honoured with only two wings, which is the count to escalate to a transfer or a third unit; a headcount ceiling on the wing coded 1 is the same command's capacity_limit rule
  • Assigning field parcels to the two halves of a rotation when adjoining parcels must be out of phase and parcels on one irrigation valve must be in phaseAgriculture
    instruments → field parcels, polarity 0/1 → which half of the rotation a parcel is planted in this season, different → an agronomic rule that two adjoining parcels must never carry the same phase in one season so a pest cannot bridge the boundary, identical → a rule that two parcels fed by a single irrigation valve must be in the same phase because the valve cannot run two schedules, violations → the number of agronomic and irrigation rules that no two-phase plan satisfies, which is the count needing a deliberate override such as a buffer strip or a valve split
  • Splitting a season's SKUs across two production lines under allergen segregation and single-copy tooling rulesFood manufacturing
    instruments → the SKUs to be scheduled for the season, polarity 0/1 → which of the two production lines a SKU is built on, different → an allergen segregation rule forcing two SKUs onto opposite lines, identical → two SKUs needing the single copy of a tool and therefore the same line, violations → the number of segregation and tooling rules no two-line split honours together, which is the count that must be covered by a validated changeover or duplicated tooling; a ceiling on HOW MANY SKUs the line coded 1 carries is the same command's capacity_limit rule, while a ceiling in volume or run hours is a continuous quantity and belongs in the companion milp command.
  • Labelling retained batches of a chiral intermediate as one enantiomer or the other from pairwise comparison assaysPharmaceutical quality control
    instruments → retained batches of the chiral intermediate, polarity 0/1 → which of the two enantiomeric forms a batch is recorded as, different → a comparison assay reporting that two batches are opposite forms, identical → an assay reporting that two batches are the same form, violations → the number of comparison assays that no consistent labelling of the batches can satisfy, which is the count of assays to repeat before the retained-sample record is signed

Measured at scale actually run

A 1,602 KB run of the same command — 100,000 instrument-polarity variables under 30,000 declared same-polarity and opposite-polarity claims — returned a broken-claim count labelled certified minimum rule violations and independently checked, which is exactly the label an audit needs before treating that count as the true number of irreducible contradictions. Read the label on your own answer rather than inferring it from the instance size.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

At 5,000 instruments and 40,000 claims the encoding is 5,000 binary variables and 40,000 pairwise rules, one rule per claim — different for an opposition, identical for an agreement — and no other structure. The reported count is exactly the number of claims the returned assignment breaks, at any size; whether it is also certified as the minimum is stated by the certainty label on that answer, so read the label rather than inferring it from the instance size, and recompute the count from the raw claim list whenever the count itself is the deliverable.

The encoding recipe (agent notes)

THIS TEACHES violations AS A MEASURED QUANTITY. Most rules examples want violations=0; here the whole point is the NUMBER — the frustration index of a signed graph ('same' edges = identical, 'opposite' edges = different), which counts the claims that are irreducibly wrong. An odd cycle of different edges is the atom of frustration: it always costs exactly 1. COMMON MISTAKES: (1) writing 'must differ' as mutual_exclusion — that only forbids both-TRUE and is silently satisfied by both-false; polarity opposition needs different, the strict XOR; (2) treating violations>0 as engine failure or an encoding bug — on contradictory evidence the minimum-violations count IS the answer (same reading as the contract-consistency example, but here the contradiction is structural, an odd cycle, not a pair of clashing clauses); (3) stretching the model past two states — pairwise identical/different over booleans is inherently the TWO-polarity balance problem; three or more classes need design; (4) verify independently by brute force on small instances: recount the broken claims of the returned assignment and confirm no assignment does better — the count, not the assignment, is what to store. READING A NONZERO COUNT HONESTLY: violations is the number of rules broken by the assignment the engine returned, and on a contradictory instance it is an UPPER BOUND on the true minimum, not guaranteed to BE the minimum. The reason is worth knowing: the search minimizes a summed penalty in which missing one rule by two units costs more than missing two rules by one unit each, so the cheapest-penalty state is not always the fewest-rules-broken state. When the count itself is your deliverable, (a) keep the instance small, (b) make each possible violation unit-sized (pairwise rules like different/identical/mutual_exclusion always are — group rules like capacity_limit and choose_one can be missed by more than one), and (c) verify by recomputing the broken rules from the raw problem, which is how this example's stored count was established. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Audit four instruments' polarity claims (three 'must be opposite' forming an odd cycle, one 'must be same') and measure how many claims are irreducibly contradictory.",
 "n": 4,
 "constraints": [
  {
   "type": "different",
   "nodes": [
    0,
    1
   ]
  },
  {
   "type": "different",
   "nodes": [
    1,
    2
   ]
  },
  {
   "type": "different",
   "nodes": [
    2,
    0
   ]
  },
  {
   "type": "identical",
   "nodes": [
    2,
    3
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 1
}

Run it

terminal
hexstellar example calibration_polarity_audit --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/calibration_polarity_audit        # the full example over HTTP

⚙️ Task Pipeline Promotion

Operations · command rules · effort flash · id: ops_task_pipeline

requires [X,Y] means X implies Y: forcing one item forces its whole chain, and the cap counts items, not money.

Six tasks can be promoted into an express phase. A task may only run in express if its prerequisite also runs in express (a precedence chain). Two of the tasks conflict and cannot both be promoted. One task must run. At most four tasks fit in the express phase. HexStellar returns a promotion set with zero violations. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is 1 when task i is promoted into the express phase. violations is 0 when every precedence, conflict, and capacity rule holds.

Where this shows up

Job-shop and pipeline stage admission (which operations are admitted together under prerequisites, conflicts and a count cap; their order and start times are not part of this decision), feature-flag rollout with dependencies, build/CI stage gating, release-train promotion.

The same encoding also solves 6

  • Choosing which dossier modules enter the next rolling regulatory submissionPharmaceutical regulatory affairs
    tasks → dossier modules, requires [X, Y] → a module that may be filed only if its supporting study report is filed too, mutual_exclusion → two labelling variants that cannot both be submitted, force_true → the module the agency has already demanded, capacity_limit k → how many modules one review cycle admits, violations 0 → a submission set that breaks none of these
  • Selecting valid rider combinations for a policy quoteInsurance
    tasks → riders, requires [X, Y] → a rider sold only on top of a base coverage, mutual_exclusion → two riders barred from being sold together, force_true → the coverage the state mandates, capacity_limit k → the maximum riders a policy may carry, violations 0 → a quotable combination
  • Shortlisting capital projects for a fiscal programmePublic infrastructure planning
    tasks → candidate projects, requires [X, Y] → a project that depends on its enabling land acquisition also being funded, mutual_exclusion → two projects competing for the same corridor, force_true → the legally mandated project, capacity_limit k → how many projects the programme admits as a COUNT of projects (a currency envelope is a continuous quantity — no rule family states a weighted ceiling, so carry it as a cost term in a milp objective, which takes no constraint list), violations 0 → an admissible shortlist
  • Choosing which instruments are powered during an observation blockSpacecraft operations
    tasks → instruments, requires [X, Y] → an instrument that may only be on when its cooler is on, mutual_exclusion → two instruments whose vibration signatures conflict, force_true → the housekeeping unit that is never off, capacity_limit k → how many units may be on at once as a COUNT of units (the watt envelope is a continuous quantity — no rule family states a weighted ceiling, so carry it as a cost term in a milp objective, which takes no constraint list), violations 0 → a valid observation block
  • Listing therapies on a formulary tier under tender and protocol constraintsHealth payer formulary management
    tasks → therapies, requires [X, Y] → a therapy listable only if its companion diagnostic is listed, mutual_exclusion → two therapies the tender forbids listing together, force_true → the therapy the national protocol mandates, capacity_limit k → the tier's listing cap, violations 0 → a compliant tier
  • Selecting which stopes enter the quarter's mine planMining
    tasks → stopes, requires [X, Y] → a stope mineable only if its access drive is developed in the same plan, mutual_exclusion → two stopes sharing one ventilation district, which cannot be active at the same time, force_true → the stope already committed to the plan, capacity_limit k → how many stopes may be active at once as a COUNT of stopes (a tonnage target is a continuous quantity — no rule family states a weighted ceiling, so carry it as a cost term in a milp objective, which takes no constraint list), violations 0 → a plan that breaks no rule

Measured at scale actually run

Scaled to 100,000 candidate items under 30,000 declared rules — prerequisites, conflicts, must-runs and the single count cap — the identical encoding returns a promotion set whose rule-violation count comes back certified as the minimum and independently re-checked, from one 1,602 KB request with peak memory of 16,588 KB.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

At 2,000 candidate items the encoding is 2,000 binary variables and one rule per stated relationship: 3,500 prerequisite edges are 3,500 requires rules (a chain of length L contributes L-1 of them), 600 conflicting pairs are 600 mutual_exclusion rules, 40 mandatory items are 40 force_true rules, and the count cap is a single capacity_limit over all 2,000 — 4,141 rules in one request. A budget measured in currency, kilograms or crew capacity is not a count of items and belongs to milp rather than capacity_limit.

The encoding recipe (agent notes)

PRECEDENCE IS AN IMPLICATION AND DIRECTION MATTERS: requires with nodes [a, b] means 'if a is 1 then b must be 1' (a ⇒ b). To say 'task X needs prerequisite Y', write requires [X, Y] — NOT [Y, X]. Getting the order backwards is the most common mistake and silently changes the meaning. A precedence CHAIN X→Y→Z is two rules: requires [X, Y] and requires [Y, Z]. 'These two conflict' is mutual_exclusion (at most one). 'This must run' is force_true. 'At most k promoted' is capacity_limit. TIP: if you expected a feasible answer but get violations > 0, your rules are over-constrained — relax one and re-run to see which rule is the bottleneck; the engine reports the count, so you can bisect. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Decide which tasks enter the fast lane, honoring prerequisites and conflicts.",
 "n": 6,
 "constraints": [
  {
   "type": "force_true",
   "nodes": [
    5
   ]
  },
  {
   "type": "requires",
   "nodes": [
    5,
    4
   ]
  },
  {
   "type": "requires",
   "nodes": [
    4,
    3
   ]
  },
  {
   "type": "requires",
   "nodes": [
    2,
    1
   ]
  },
  {
   "type": "requires",
   "nodes": [
    1,
    0
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    3
   ]
  },
  {
   "type": "capacity_limit",
   "k": 4,
   "nodes": [
    0,
    1,
    2,
    3,
    4,
    5
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example ops_task_pipeline --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/ops_task_pipeline        # the full example over HTTP

Quantum & Physics

E Known Coupled Ground State

Quantum & Physics · command feel · effort flash · id: energy_known_ground_state

A planted coupled system has a recomputable global energy floor.

Find the lowest-energy assignment of a coupled binary system with a closed small-instance check. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

enumerate 2^n states for the toy input and recompute every term

Where this shows up

Materials science, Operations, Physics

The same encoding also solves 3

  • Binary material configurationMaterials science
    sites/interactions → field/couple
  • Coupled on/off policyOperations
    choices/dependencies → state/couple
  • Small Ising auditPhysics
    spins/bonds → state/couple

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Find the lowest-energy assignment of a coupled binary system with a closed small-instance check.",
 "n": 8,
 "field": {
  "0": -3,
  "3": 2,
  "7": -1
 },
 "couple": [
  [
   0,
   1,
   -5
  ],
  [
   1,
   2,
   -2
  ],
  [
   2,
   3,
   4
  ],
  [
   3,
   4,
   -3
  ],
  [
   4,
   5,
   2
  ],
  [
   5,
   6,
   -4
  ],
  [
   6,
   7,
   -2
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "energy": -17,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example energy_known_ground_state --format json | hexstellar solve feel
curl -s https://api.hexstellar.com/api/v1/examples/energy_known_ground_state        # the full example over HTTP

φ Controlled Phase Hypothesis

Quantum & Physics · command phase · effort flash · id: physics_controlled_phase

Phase output stays explicitly hypothetical and requests a boundary-condition check.

Classify a controlled coupled-site model while preserving hypothesis language. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

repeat under open and periodic boundaries and inspect the gap

Where this shows up

Condensed-matter physics, Photonics, Systems science

The same encoding also solves 3

  • SSH-chain screeningCondensed-matter physics
    hoppings → couplings
  • Coupled-mode transitionPhotonics
    waveguide couplings → couplings
  • Network regime indicatorSystems science
    weighted chain → couplings

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Classify a controlled coupled-site model while preserving hypothesis language.",
 "sites": [
  0,
  0,
  0,
  0
 ],
 "couplings": [
  [
   0,
   1,
   1.0
  ],
  [
   1,
   2,
   2.0
  ],
  [
   2,
   3,
   1.0
  ]
 ],
 "fill": 2
}

Expected (engine-verified)

expected.json
{
 "answer": "topological / critical (edge modes or gap closed)",
 "g_v": 0.3398,
 "gap": 0.8284271247,
 "certainty": "heuristic (hypothesis — verify; no independent optimality certificate)"
}

Run it

terminal
hexstellar example physics_controlled_phase --format json | hexstellar solve phase
curl -s https://api.hexstellar.com/api/v1/examples/physics_controlled_phase        # the full example over HTTP

🧊 Quantum Error-Correction Decoder

Quantum & Physics · command optimize · effort flash · id: quantum_error_decoder

One boolean per pair, not per item: 'covered exactly once' expands to -M on each incident pairing and +2M wherever two share an item.

A fault-tolerant quantum computer reads a stream of syndrome measurements; each decode window leaves a set of 'defects' that must be paired up along likely error chains, and the most probable error is the pairing whose total chain weight is smallest. Here four defects (a, b, c, d) have six candidate pairings with weights ab=1, cd=1, ac=2, bd=2, ad=3, bc=3. HexStellar returns the minimum-weight perfect matching — pair a with b and c with d, total weight 2 — as a certified optimum. The decoder must keep pace with the machine's error rate, which is why decode windows are kept small. The solve itself runs on the HexStellar service; the shipped client is a transparent HTTPS transport, never a local solver, so size the window and the effort budget for a network round-trip. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

Nodes are candidate pairings: 0=a-b, 1=c-d, 2=a-c, 3=b-d, 4=a-d, 5=b-c. answer[i] is 1 when that pairing is part of the decoded error. energy is the minimized objective: total chain weight minus one fixed reward per defect covered — here 2 − 4×10 = −38. Recover the physical answer by decoding which pairings are on and checking each defect appears in exactly one.

Where this shows up

Surface-code syndrome decoding, and every other guise of minimum-weight matching: pairing sensor anomalies to common causes, matching pickups to dropoffs, kidney-exchange pairing, task-to-worker pairing where each side is used exactly once.

The same encoding also solves 8

  • Kidney paired donation: choosing which two-way swaps to runTransplant medicine
    item → an incompatible donor-recipient pair in the pool, candidate pairing → a two-way swap between two such pairs, chain weight → minus the predicted graft-survival score of that swap, M → the coverage penalty on each pool member; because not every member must be matched, drop the -M from the incident pairings' linear terms and keep the +2M repulsion, which turns exactly-once into at-most-once
  • Backhaul pairing: matching each outbound load with a return load so no truck runs emptyFreight
    item → a load on the board, candidate pairing → an outbound-plus-return combination one truck can run, chain weight → deadhead distance between the outbound drop and the return pickup, M → the coverage penalty putting each load in exactly one combination
  • Flip-flop banking: pairing single-bit registers into two-bit cells that share a clock driverChip design
    item → a flip-flop, candidate pairing → a merge of two flip-flops into one two-bit cell, chain weight → added wirelength plus the timing slack the merge gives up, M → the coverage penalty putting each flip-flop in exactly one cell
  • Building one round of fixtures so every team plays exactly onceSports league operations
    item → a team, candidate pairing → a fixture between two teams, chain weight → travel distance plus a penalty for repeating a recent fixture, M → the coverage penalty putting every team in exactly one fixture
  • Selective assembly: pairing shafts with bushings so each fitted clearance is closest to nominalPrecision manufacturing
    item → one measured part, candidate pairing → a shaft-with-bushing fit, chain weight → absolute deviation of that fit's clearance from nominal, M → the coverage penalty using each part exactly once; a two-sided pool simply omits the shaft-shaft and bushing-bushing booleans
  • Data association: attaching this scan's detections to the existing tracksRadar and air-traffic tracking
    item → a track or a detection, candidate pairing → a track-to-detection association inside the gate, chain weight → the gated statistical distance between the track's prediction and the detection, M → the coverage penalty using each track and each detection exactly once; when the two counts differ, add dummy items whose pairings carry the cost of leaving a track unassigned
  • Pairing officers into two-person patrol units for a rosterPublic safety
    item → an officer on the roster, candidate pairing → a two-officer unit, chain weight → the incompatibility cost of that unit across language, certification and seniority mix, M → the coverage penalty putting each officer in exactly one unit
  • Assigning dormitory roommates from a compatibility surveyEducation
    item → a student, candidate pairing → a possible room-sharing pair, chain weight → the surveyed incompatibility score, M → the coverage penalty putting each student in exactly one room; this minimizes total incompatibility, which is a different requirement from stability, and a stability rule is not this encoding

Measured at scale actually run

Twenty thousand candidate pairings held apart by 200,000 shared-defect exclusions decode from one 3,801 KB request, and the answer arrives labelled heuristic rather than certified, so confirm every defect appears in exactly one chosen pairing before the decode is trusted.

Instance
20,000 variables · 20,000 linear terms · 200,000 pair terms
Answer
heuristic (labelled)
Engine time
112 ms (111 ms–119 ms, n=3)
Peak memory
17.2 MB
Request
3,801 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only optimize --sizes target

How the encoding grows

Variables are candidate pairings, not items: 60 items with every pairing allowed is 1,770 booleans and 102,660 quadratic terms, because each item contributes C(59,2) = 1,711 mutually exclusive pairs of its own incident pairings. Candidate lists are normally gated by a distance cutoff, so keeping the six nearest partners per item sends roughly 180 booleans and 900 quadratic terms; the reported objective sits one M per item below the physical total, so add 60M back to read total weight, and the certainty label states whether that pairing was certified by exhaustion.

The encoding recipe (agent notes)

THIS TEACHES MATCHING — a structure the constraint types don't name directly. THE ENCODING RECIPE: one boolean per candidate PAIR (not per item). 'Each defect is covered exactly once' becomes a big-M penalty per defect: M·(sum of its incident pairings − 1)², which expands to −M on the linear term of each incident pairing (a pairing touches two defects, so its total linear bias is weight − 2M, here weight − 20) and +2M on every quadratic pair of pairings that share a defect. The chain weights ride on top of the linear terms, so the engine minimizes total weight AMONG perfect matchings. Pick M comfortably larger than any weight (here M=10 vs max weight 3) so no weight saving can ever pay for leaving a defect uncovered or double-covered. COMMON MISTAKES: (1) making the node an item instead of a pair — matching lives on the EDGES; a boolean per defect cannot express 'a with b'; (2) M too small — the solver 'saves' weight by breaking coverage; too enormous — the weights vanish into rounding and every matching looks equal; start at ~10× the largest weight; (3) forgetting that two pairings sharing a defect must repel — that +2M quadratic term IS the mutual exclusion, derived from the squared penalty rather than written by hand; (4) reading energy as the physical weight — subtract the constant the squared penalties dropped (one M per defect) to recover it, or just decode the answer and re-add the chosen weights. Hard rules can express 'a perfect matching exists' (choose_one per defect over its pairings), but only optimize finds the CHEAPEST one — feasibility and optimality are different questions. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Pair up error-syndrome defects along the cheapest chains — minimum-weight perfect matching as an objective.",
 "n": 6,
 "linear": {
  "0": -19,
  "1": -19,
  "2": -18,
  "3": -18,
  "4": -17,
  "5": -17
 },
 "quadratic": [
  [
   0,
   2,
   20
  ],
  [
   0,
   4,
   20
  ],
  [
   2,
   4,
   20
  ],
  [
   0,
   3,
   20
  ],
  [
   0,
   5,
   20
  ],
  [
   3,
   5,
   20
  ],
  [
   1,
   2,
   20
  ],
  [
   1,
   5,
   20
  ],
  [
   2,
   5,
   20
  ],
  [
   1,
   3,
   20
  ],
  [
   1,
   4,
   20
  ],
  [
   3,
   4,
   20
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "energy": -38,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example quantum_error_decoder --format json | hexstellar solve optimize
curl -s https://api.hexstellar.com/api/v1/examples/quantum_error_decoder        # the full example over HTTP

⚛️ Spin Hamiltonian Spectrum

Quantum & Physics · command spectrum · effort flash · id: quantum_spin_spectrum

Any symmetric matrix is a Hamiltonian: the answer is N levels, not 2^N states, and when the ground level is 0 the gap IS the connectivity.

A four-state symmetric Hamiltonian describing a small coupled spin system. HexStellar returns the exact eigenvalues — the energy levels — with the ground energy and the spectral gap (the distance from the ground state to the first excited state, which governs how the system behaves). This is the linear-algebra heart of quantum and condensed-matter simulation. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer.ground_energy is the lowest level; answer.spectral_gap the gap above it; eigenvalues the full ladder.

Where this shows up

Quantum simulation, materials science, molecular energy levels, stability analysis.

The same encoding also solves 7

  • Screening a structure's natural frequencies against a known forcing frequencyStructural engineering
    spin Hamiltonian → the mass-normalized stiffness matrix M^-1/2 K M^-1/2 (do that normalization first, so one symmetric matrix goes in), diagonal → each degree of freedom's own stiffness, off-diagonal → the coupling between connected degrees of freedom, eigenvalues → the squared natural frequencies, ground energy → the fundamental mode's squared frequency, spectral gap → the separation of the first two modes, where a small gap warns of closely spaced modes that beat under excitation. Mode SHAPES are not returned; this reads the frequency ladder
  • Molecular orbital levels of a conjugated ringChemistry
    Hamiltonian → the Huckel matrix (the 4-site ring in this example is exactly one), diagonal → each atom's alpha offset, off-diagonal → the beta resonance integral on every bond, eigenvalues → the orbital energy ladder, ground energy → the lowest occupied level, spectral gap → the separation of the two lowest levels; the HOMO-LUMO separation is read off the returned ladder at your own electron count
  • Checking whether an estimated covariance matrix is usable before it drives an allocationFinance
    Hamiltonian → the asset covariance or correlation matrix, diagonal → each asset's variance, off-diagonal → the pair covariance, eigenvalues → the variance carried by each principal direction, ground energy → the SMALLEST eigenvalue, whose sign is the positive-semidefinite test (negative means the estimate is not a valid covariance and must be repaired before anything is built on it), spectral gap → the separation of the two smallest directions; the top-end separation that says how dominant the market-wide factor is comes from the returned eigenvalues array, not from the named gap field
  • Measuring how hard a network is to disconnectNetwork engineering
    Hamiltonian → the graph Laplacian, diagonal → each node's weighted degree, off-diagonal → the negated link weight, eigenvalues → the Laplacian spectrum, ground energy → exactly 0 for a connected graph, and the count of zeros in the returned ladder is the number of connected components, spectral gap → because the ground level is 0, the reported gap IS the algebraic connectivity, which bounds how cheap any cut can be. The cut itself is not here — that is maxcut, the partition-into-two shape
  • Conditioning a kernel/Gram matrix before it is inverted in a fitMachine learning
    Hamiltonian → the Gram matrix of your kernel over the training points, diagonal → each point's self-similarity, off-diagonal → the pairwise kernel value, eigenvalues → the spectrum, ground energy → the smallest eigenvalue, which tells you how much ridge the inverse needs to be well-posed and, against the largest value in the returned array, gives the condition number, spectral gap → the separation of the two SMALLEST eigenvalues, i.e. how nearly degenerate the flattest direction is; the effective rank - where the ladder steps at the TOP - is read off the returned eigenvalues array, not from the named gap field.
  • Whether a modelled ecological community returns to equilibrium after a shockEcology
    Hamiltonian → the symmetric community interaction matrix, diagonal → each species' self-regulation, off-diagonal → the pairwise interaction strength, eigenvalues → the stability spectrum, the LARGEST value in the returned ladder → whether any perturbation direction grows (stable only while it stays negative), ground energy → the most strongly damped direction, spectral gap → the separation between the two most damped directions. Read the top of the ladder from eigenvalues; the named ground and gap fields describe its bottom
  • Locating a power network's slow inter-area oscillation modesEnergy
    Hamiltonian → M^-1/2 B M^-1/2, the network's susceptance Laplacian B congruence-scaled by the diagonal bus-inertia matrix M - that transform is symmetric by construction and preserves the eigenvalues of M^-1 B, whereas averaging M^-1 B with its transpose is a different matrix with different levels, so do not simply symmetrize it, diagonal → each bus's inertia-scaled total susceptance, off-diagonal → the negated inertia-scaled line susceptance between two buses, eigenvalues → the squared mode frequencies, ground energy → the 0 mode, the uniform frequency drift of the whole system, spectral gap → since the ground level is exactly 0, the reported gap IS the slowest inter-area mode, the one that governs how the system swings back.

Measured at scale actually run

The same encoding scaled to an 800-state spin Hamiltonian — one dense symmetric matrix of 640,000 entries submitted as a single 2,161 KB request — returns the complete 800-level energy ladder with its ground energy and the gap above it, labelled an operation result: optimality does not apply to a spectrum, and no independent proof is attached, so the check to run on your side is det(H - lambda I) = 0.

Instance
800 variables · 640,000 matrix entries
Answer
operation result
Engine time
8.2 s (8.1 s–8.2 s, n=3)
Peak memory
9.2 MB
Request
2,161 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only spectrum --sizes target

How the encoding grows

The identical shape at N = 800 is one symmetric matrix of 640,000 numbers — 320,400 of them independent — submitted as a single 2,160 KB request, and the answer is a ladder of exactly 800 levels with the lowest of them and the gap above it named. The response length is N, never 2^N: the readout is over the operator, not over its state space. It comes back as an operation result — optimality does not apply to a spectrum, and no independent proof is attached, so the check to run is det(H - lambda I) = 0. Two scoping facts follow from the shape: the matrix is dense, so all N^2 numbers are transmitted rather than only the upper triangle; and eigenVECTORS are not part of the response, so a question about WHICH state rather than which level is a different encoding.

The encoding recipe (agent notes)

THE ENCODING RECIPE: spectrum takes a real symmetric matrix and returns its exact eigenvalue ladder — ground energy, the spectral gap above it, and every level. It CHARACTERIZES a system; it does not choose a configuration. COMMON MISTAKES: (1) feeding a non-symmetric matrix — symmetrize first or the physics is meaningless; (2) using spectrum when you wanted a decision — it returns energy LEVELS, not which state achieves them, so 'find the densest cluster / best partition' questions belong to maxcut/optimize/rules, not here; (3) ignoring what the gap tells you — a small spectral gap means near-degenerate competing states (a fragile landscape, slow mixing, ambiguous ground state), which is exactly the diagnostic you want before trusting an optimization on the same matrix; (4) scale — exact ladders are for small dense systems; use it as a magnifying glass on a subsystem, not on the full 10,000-node problem. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "The ground-state energy, spectral gap, and full energy ladder of a spin system.",
 "matrix": [
  [
   -2,
   1,
   0,
   1
  ],
  [
   1,
   -2,
   1,
   0
  ],
  [
   0,
   1,
   -2,
   1
  ],
  [
   1,
   0,
   1,
   -2
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "answer": {
  "ground_energy": -4.0,
  "spectral_gap": 2.0
 },
 "eigenvalues": [
  -4.0,
  -2.0,
  -2.0,
  0.0
 ]
}

Run it

terminal
hexstellar example quantum_spin_spectrum --format json | hexstellar solve spectrum
curl -s https://api.hexstellar.com/api/v1/examples/quantum_spin_spectrum        # the full example over HTTP

∑ Known Entropy Spectrum

Quantum & Physics · command entropy · effort flash · id: science_known_entropy

A diagonal correlation spectrum gives an independently recomputable entropy.

Compute the subsystem entropy of a correlation matrix with a known spectrum. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

diagonalize independently and sum -p log p -(1-p) log(1-p)

Where this shows up

Quantum information, Statistics, Signal processing

The same encoding also solves 3

  • Entanglement entropy of a Gaussian subsystemQuantum information
    correlation matrix → correlation
  • Diversity of a two-class mixtureStatistics
    class probabilities → diagonal occupations
  • Information content of independent modesSignal processing
    mode occupations → eigenvalues

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Compute the subsystem entropy of a correlation matrix with a known spectrum.",
 "correlation": [
  [
   0.5,
   0.0
  ],
  [
   0.0,
   0.5
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "answer": {
  "entropy_nats": 1.38629436112,
  "entropy_bits": 2.0
 },
 "certainty": "operation result (optimality not applicable; no independent proof checked)"
}

Run it

terminal
hexstellar example science_known_entropy --format json | hexstellar solve entropy
curl -s https://api.hexstellar.com/api/v1/examples/science_known_entropy        # the full example over HTTP

Real Estate

🏢 Maintenance Hub Coverage

Real Estate · command rules · effort flash · id: hub_corridor_coverage

Activate exactly k hubs so every corridor has an active endpoint — 'at least one of the pair' built from complements.

A property operator runs five maintenance hubs arranged around a ring of service corridors, and budget allows exactly three to stay active. The requirement is a COVERING one: every corridor must keep at least one of its two endpoint hubs active. Hard rules have no at-least constraint — and this example shows the gadget that builds one anyway: give each hub a shadow 'inactive' boolean tied to it by different (a true boolean complement), then forbid the two INACTIVE shadows of a corridor's endpoints from being true together with mutual_exclusion. 'Not both endpoints inactive' is exactly 'at least one endpoint active'. HexStellar returns a valid cover (here hubs 1, 3, 4); the five satisfying activations are precisely the five minimum vertex covers of the 5-cycle, verified by brute force. This is Vertex Cover — Karp 1972 — expressed with nothing but different, mutual_exclusion, and choose_exactly. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

Nodes 0-4 are the hub active flags, nodes 5-9 their complement ('inactive') shadows. answer[i] (i<5) is 1 when hub i stays active. violations is 0 when exactly three hubs are active, every shadow is the true opposite of its hub, and no corridor has both endpoints inactive. Five distinct valid covers exist — test the invariant.

Where this shows up

Facility and campus maintenance coverage, security-guard or camera posts covering passages, network monitors covering links, code reviewers covering module boundaries, on-call rotations where every dependency edge needs an awake owner — every covering-shaped requirement ('each edge needs at least one chosen endpoint').

The same encoding also solves 7

  • Contact-tracing triage where every recorded contact pair must have at least one of the two people testedPublic Health
    hub active flags → people, inactive shadows → the 'not tested' indicator bound to each person by different, corridor → a recorded contact between two people, exclusion on the two shadows → that contact pair may not both go untested, choose_exactly k → the test kits on hand
  • Rolling out hardened endpoint controls so every trust relationship has at least one hardened endCybersecurity
    hub active flags → hosts receiving the hardened build, inactive shadows → the 'left unhardened' indicator, corridor → a domain trust or peering relationship between two hosts, exclusion on the two shadows → a relationship may not have both ends unhardened, choose_exactly k → the licences funded this cycle
  • Contract testing where every service-to-service boundary needs a suite on at least one sideSoftware Testing
    hub active flags → services that own a contract suite, inactive shadows → the 'no suite here' indicator, corridor → a call boundary between two services, exclusion on the two shadows → a boundary may not have both sides untested, choose_exactly k → the number of suites the team commits to maintaining
  • Pressure-sensor placement so every pipe is instrumented at one of its two end junctionsWater Utilities
    hub active flags → junctions fitted with a sensor, inactive shadows → the 'uninstrumented junction' indicator, corridor → a pipe joining two junctions, exclusion on the two shadows → a pipe may not have both ends uninstrumented, choose_exactly k → the sensors in the capital budget
  • Staffing inspection posts so every trade lane is inspected at one of its two portsCustoms and Trade
    hub active flags → ports with a staffed inspection post, inactive shadows → the 'unstaffed port' indicator, corridor → a lane connecting two ports, exclusion on the two shadows → a lane may not run between two unstaffed ports, choose_exactly k → the posts the agency can staff
  • Fitting detection equipment so every track section between two interlockings is monitored from one endRail
    hub active flags → interlockings retrofitted with detection equipment, inactive shadows → the 'not retrofitted' indicator, corridor → a track section between two interlockings, exclusion on the two shadows → a section may not have both ends unfitted, choose_exactly k → the retrofits funded in the programme
  • Buying habitat parcels so every wildlife corridor has at least one protected endpoint patchConservation
    hub active flags → habitat patches placed under protection, inactive shadows → the 'unprotected patch' indicator, corridor → a migration corridor linking two patches, exclusion on the two shadows → a corridor may not link two unprotected patches, choose_exactly k → the parcels the land trust can acquire

Measured at scale actually run

The same complement gadget at production size — 100,000 hub and shadow booleans across 10,000 declared groups, 30,000 coverage and budget rules, 1.6 MB in one request — returns an activation whose rule-violation count is certified minimal and independently checked, so a zero there is the proof that every corridor holds an active endpoint within the declared budget.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical gadget on 5,000 items and 40,000 pairwise requirements is 10,000 booleans — one active flag plus one complement shadow per item — with 5,000 different rules, 40,000 mutual_exclusion rules (one per requirement pair), and a single choose_exactly for the budget, sent as one request. Counts follow the item and pair totals only. k is declared rather than minimized: sweep k downward and re-solve, or price the items in this command's optional linear objective. A requirement over more than two items (at least 2 of these 7) is outside the pairwise gadget and belongs to the cover command. Certification is reported per answer and is not decided by graph size: a 100,000-boolean rule set carrying 30,000 rules has come back certified, so read the label the answer carries rather than assuming a bigger graph must be a labelled heuristic.

The encoding recipe (agent notes)

THE COMPLEMENT GADGET — the most important trick in this catalogue. Hard rules cannot say 'at least one of these' directly, but they CAN say it for PAIRS: create a shadow boolean per item, bind it with different (shadow = NOT item, a real complement, not an implication), and then mutual_exclusion on the two SHADOWS of a pair means 'not both absent' = 'at least one present'. That is Vertex Cover / edge covering, fully expressible today. COMMON MISTAKES: (1) putting the mutual_exclusion on the ACTIVE endpoints — that is Independent Set, the exact OPPOSITE condition (enemies apart vs. every edge owned); check which side of the graph your requirement lives on; (2) building the complement with two requires — implications leak (both false satisfies A⇒B); only different forces the strict opposite; (3) attaching choose_exactly k=3 to all ten nodes — the cardinality belongs to the five ACTIVE flags only (the shadows then count themselves automatically); (4) know the gadget's limit — it expresses at-least-one-of-TWO (per edge); a general 'at least k of this group' for k≥2 or wide groups still needs a different formulation, so don't stretch the gadget past pairwise coverage; (5) minimizing the number of active hubs (true MINIMUM vertex cover) is an objective — sweep k downward re-solving, or move to optimize with per-hub costs. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Activate exactly 3 of 5 maintenance hubs on a corridor ring so every corridor keeps at least one active endpoint (vertex cover via the different-complement gadget).",
 "n": 10,
 "constraints": [
  {
   "type": "choose_exactly",
   "k": 3,
   "nodes": [
    0,
    1,
    2,
    3,
    4
   ]
  },
  {
   "type": "different",
   "nodes": [
    0,
    5
   ]
  },
  {
   "type": "different",
   "nodes": [
    1,
    6
   ]
  },
  {
   "type": "different",
   "nodes": [
    2,
    7
   ]
  },
  {
   "type": "different",
   "nodes": [
    3,
    8
   ]
  },
  {
   "type": "different",
   "nodes": [
    4,
    9
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    5,
    6
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    6,
    7
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    7,
    8
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    8,
    9
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    9,
    5
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example hub_corridor_coverage --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/hub_corridor_coverage        # the full example over HTTP

Robotics

⚖️ Counterweight Jettison & Balance

Robotics · command milp · effort flash · id: robotics_balance_jettison

An equality becomes (Σaᵢxᵢ − T)² in the objective: cross terms 2aᵢaⱼ to quadratic, a²y² doubled into diag, binary a²x² into linear.

A robot wants to jettison ballast (each release is worth 200) but must keep its moment balanced: 10·(first weight) + 20·(second weight) + 5·(arm position) must equal zero, with the arm limited to ±3. The milp command has no constraint list — so the equality becomes part of the objective by SQUARING it: (10x₀ + 20x₁ + 5y)² is zero exactly when the robot is balanced and grows fast otherwise. Expanding that square gives the linear, diagonal, and cross terms below (binaries simplify because x² = x). HexStellar returns: release the first weight, keep the second, slide the arm to −2.0 — perfectly balanced, objective −200. Releasing both is impossible to balance within the arm's travel; releasing none wastes the opportunity. Brute force over the four binary patterns with the continuous part solved exactly confirms it. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is [release weight 0 (0/1), release weight 1 (0/1), arm position (real, in ±3)]. objective is the squared moment (0 when balanced) minus the jettison rewards — here −200, meaning one weight released with a perfectly zero moment.

Where this shows up

Ballast and counterweight management, robot payload drops, crane and forklift stability, spacecraft mass-property trim, blending to an exact target ratio, any 'this weighted sum must hit a target' requirement on a solver that only takes an objective.

The same encoding also solves 6

  • Trimming a spacecraft's mass properties before a burnAerospace
    released weights → jettisonable items, one binary each, coefficients 10/20 → each item's mass x moment arm, the sliding arm → a translating ballast or propellant transfer bounded by its rail travel, 'moment = 0' → the squared equality expanded into linear/diag/quadratic, jettison reward → the delta-v value of shedding that item, balance term 0 → the trim is achievable inside the rail
  • Meeting a truck's axle-load split by choosing pallets to leave behind and setting the sliding tandemLogistics
    released weights → pallets that may be left on the dock, one binary each, coefficients → each pallet's weight x its distance from the kingpin, the sliding arm → the tandem axle position within its rail travel, 'moment = 0' → the squared deviation from the legal axle split, the linear term on each binary → the freight revenue you FORFEIT by leaving that pallet, written POSITIVE so dropping freight costs the objective (the base example's negative reward belongs to the opposite convention, where the binary means shed and shedding is what you want), objective floor 0 → a legal load exists without dropping more freight. A legal MAXIMUM is an inequality, not an equality: target the limit and read the residual rather than assuming it is enforced.
  • Rebalancing a book to zero net factor exposureFinance
    released weights → lots that may be closed, one binary each, coefficients → each lot's beta x notional, the sliding arm → the size of a continuously sized index-future overlay bounded by the margin you may post, 'moment = 0' → net portfolio beta of zero as the squared equality, jettison reward → the fee or tax credit for closing that lot, balance term 0 → exact neutrality is reachable with the overlay you are allowed to hold
  • Blending a scrap charge to an exact alloy specificationMetals
    released weights → optional scrap lots, one binary each whose linear term is the lot's cost, coefficients → m_i x (c_i - target), each lot's mass times its DEVIATION from the target grade, because a composition is a ratio and only in that form is 'hit the grade exactly' the linear equality sum m_i (c_i - target) = 0 that this shape squares, the sliding arm → a continuously dosed ferro-alloy addition bounded by the feeder's range, entered with the same deviation coefficient, 'moment = 0' → that squared equality, objective floor 0 → the specification is reachable from the lots on hand. Two controlled elements are two squared terms summed into the same coefficient arrays.
  • Trimming an analog network to a target conductanceElectronics
    released weights → switchable trim elements, one binary each whose linear term is the die area cost of enabling it, coefficients → each element's conductance contribution, the sliding arm → the continuously adjustable element within its trim range, 'moment = 0' → the target total conductance as the squared equality, objective floor 0 → the target sits inside the achievable range
  • Placing balance weights on a rotorRotating machinery
    released weights → candidate bolt-hole weights, one binary each, coefficients → mass x radius x cos(angle) for the x moment and mass x radius x sin(angle) for the y moment, the sliding arm → a continuously SIZED trim mass at one fixed known angular station, whose contributions m*r*cos(theta) and m*r*sin(theta) are linear in m (a continuously POSITIONED weight is not usable here, because angle enters through cos/sin and is not linear, and sliding a collar along the shaft does not change the x-y imbalance at all), 'moment = 0' → TWO squared equalities, x and y, summed into one objective over the same pairs, the linear term on each binary → the POSITIVE cost of installing that weight, objective floor 0 → residual imbalance can be driven to zero with the holes available.

Measured at scale actually run

At 1,500 jettisonable items and 1,500 continuously sized trims, the squared balance equalities expand into 12,000 quadratic pairs in a 350 KB request, and the answer names which items to release and where each trim sits. The label is heuristic rather than certified, so recompute Σaᵢxᵢ from the returned answer rather than reading a zero balance term as proof the equality was met.

Instance
1,500 binary · 1,500 continuous · 12,000 pair terms
Answer
heuristic (labelled)
Engine time
37 ms (36 ms–37 ms, n=3)
Peak memory
3.1 MB
Request
350 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only milp --sizes target

How the encoding grows

The identical shape at 60 discrete items, 3 continuous trims and 2 target equalities is 63 variables: 60 linear entries (each binary's a_i^2 x_i^2 collapses there because x^2 = x), 3 diag entries, and at most C(60,2) = 1,770 binary-binary + 60x3 = 180 binary-continuous + C(3,2) = 3 continuous-continuous = 1,953 quadratic pairs. A second equality adds no new pairs — its coefficients are summed into the same 1,953 — so the request grows with the item count, not with the number of targets. milp labels this heuristic: a zero balance term in the returned objective is the statement that the equality is met exactly, and you re-derive the continuous optimum for the returned pattern and its one-flip neighbours to confirm.

The encoding recipe (agent notes)

TWO TECHNIQUES. FIRST — AN EQUALITY BECOMES A SQUARE: milp takes no constraints, so express Σaᵢxᵢ = T as (Σaᵢxᵢ − T)² inside the objective. Expand it by hand: cross terms 2aᵢaⱼ go in quadratic, the continuous square a²y² goes in diag REMEMBERING the ½ convention (a coefficient of 25y² is written diag 50), and for BINARIES x² = x so the a²x² term collapses into linear — that collapse is what agents miss. A zero BALANCE term means the equality is satisfiable, but the objective is not that term: the jettison rewards or the enabling costs shift it off zero in either direction (here the floor is −200 with the balance exactly 0, and under a positive-cost convention the floor can be positive while the equality is met exactly), so isolate the balance by recomputing Σaᵢxᵢ from the returned answer instead of reading the objective's sign. SECOND — SIZE YOUR REWARDS AGAINST THE LANDSCAPE: this instance is honest about a real trap. With the jettison reward set to 30 instead of 200, the engine returns the do-nothing answer (objective 0) even though releasing one weight and re-sliding the arm scores −30. Why: flipping a binary while the continuous variable still sits at its OLD value looks worse (+70), so the improving move is hidden behind a barrier. milp reports certainty: heuristic precisely for this — so (a) make the reward for a discrete change exceed the un-adjusted penalty of that change, (b) probe the neighbors yourself (re-solve with a binary pinned) when a returned answer looks suspiciously inert, and (c) never treat a heuristic objective as proven. COMMON MISTAKES: passing the raw equality as a constraint list (there is none); forgetting the ½ in diag; leaving the x² term in quadratic as [i,i,w] instead of collapsing it into linear; and reading a do-nothing answer as 'nothing is possible' rather than checking the barrier. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Decide which counterweights to jettison while a sliding arm keeps the total moment exactly zero, with the balance equality encoded as a squared objective term.",
 "vars": [
  {
   "domain": "binary"
  },
  {
   "domain": "binary"
  },
  {
   "domain": "continuous",
   "lo": -3,
   "hi": 3
  }
 ],
 "linear": {
  "0": -100,
  "1": 200
 },
 "diag": {
  "2": 50
 },
 "quadratic": [
  [
   0,
   1,
   400
  ],
  [
   0,
   2,
   100
  ],
  [
   1,
   2,
   200
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "objective": -200.0,
 "certainty": "heuristic (hypothesis - verify; global optimum for a convex problem, otherwise a strong local optimum)"
}

Run it

terminal
hexstellar example robotics_balance_jettison --format json | hexstellar solve milp
curl -s https://api.hexstellar.com/api/v1/examples/robotics_balance_jettison        # the full example over HTTP

🤖 Robotic Cell Layout

Robotics · command qap · effort flash · id: robotics_cell_layout

"Distance" is any number per pair of places - pocket index cost, acoustic delay in ms, spectral overlap; the answer stays one-to-one.

Five machines pass work-in-progress between each other (the flow matrix). Five physical stations sit at fixed distances (the distance matrix). HexStellar assigns each machine to a station so the total flow×distance — the robot travel and conveyor cost — is minimized. This is the Quadratic Assignment Problem, the core of factory and warehouse layout. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is the station chosen for machine i; cost is the total flow×distance.

Where this shows up

Assembly-line layout, warehouse slotting, chip floor-planning, hospital ward placement.

The same encoding also solves 11

  • Tool-magazine pocket assignment on a CNC machining centerMachining
    flow → how often tool i and tool j are called consecutively in the NC program, dist → index cost of rotating between pockets a and b, answer[i] → the pocket for tool i, cost → total magazine movement over the program
  • Keyboard layout for a language corpusHuman-computer interaction
    flow → digram count of the letter pair (i,j) in the corpus (whole counts, not fractional frequencies — flow and dist carry integer entries), dist → finger-travel cost from key position a to key position b (the cost formula sums ordered pairs, so an asymmetric travel table is fine), answer[i] → the key position for letter i
  • PCB component placement for the shortest total trace lengthElectronics hardware
    flow → number of nets between component i and component j in the netlist, dist → board distance between mounting sites a and b, answer[i] → the site for component i, cost → total net-weighted trace length
  • Assigning signal groups to package balls to keep crosstalk-prone pairs apartSemiconductor packaging
    flow → crosstalk susceptibility between signal group i and group j, dist → proximity of balls a and b ((widest pitch − pitch between them)), answer[i] → the ball for signal group i; note the inversion — the same command pulls pairs together when flow is traffic and dist is distance, and pushes them apart when flow is a hazard and dist is closeness
  • Landmark correspondence between two 3-D scansComputer vision
    flow → pairwise distance between landmarks i and j in scan A, dist → (largest pairwise distance − distance between landmarks a and b in scan B), answer[i] → the scan-B landmark matched to scan-A landmark i; minimizing the products maximizes the sum of dA x dB, which is the least-squares distortion match because the sum of dB squared is identical for every permutation
  • Placing each airline's gate block along an airport concourseAirport operations
    flow → passengers connecting between airline i and airline j on an average day (whole counts), dist → walking distance in metres between gate block a and gate block b, answer[i] → the gate block given to airline i, cost → total passenger-metres walked on connections across the terminal. Block eligibility (a block too short for an airline's widebodies) is not a qap term: declare those pairings with rules, fix the airlines they force, then map the remaining airlines and blocks here — equal counts, padding with a zero-flow airline if blocks outnumber airlines.
  • Laying out seed-trial varieties across a grid of field plots so cross-pollinating pairs sit far apartAgronomy and plant breeding
    flow → cross-pollination risk weight between variety i and variety j on a whole-number scale (zero for pairs that cannot cross — flow and dist carry integer entries), dist → (longest separation on the grid − metres between plot a and plot b), so a risky pair is charged only when it lands close, answer[i] → the plot assigned to variety i, cost → total pollination exposure over the trial. Same inversion the packaging entry uses, applied to a field instead of a package.
  • Assigning transmitters in a dense cell cluster to the channel slots of a fixed plan, one slot eachWireless network planning
    flow → measured interference coupling between transmitter i and transmitter j on a whole-number scale (how much of one's signal lands inside the other's service area), dist → spectral overlap between channel slot a and slot b, decaying with the number of slots apart and zero once they are far enough apart to stop interfering, answer[i] → the channel slot given to transmitter i, cost → total interference the plan carries. The 'distance' matrix is spectral rather than geometric; the encoding does not care which, only that it is a number per pair of locations. Because the plan gives one slot each, no two transmitters ever share a slot and only the off-diagonal overlaps are charged.
  • Seating the orchestra's sections on the risers of a concert shellPerforming arts and live sound
    flow → how many scored passages in the season's repertoire require section i to lock with section j (a whole count taken off the scores), dist → acoustic delay in whole milliseconds between riser a and riser b (flow and dist carry integer entries), answer[i] → the riser given to section i, cost → total delay-weighted coupling the ensemble has to play through.
  • Shelving closed-stack collections in a repository so a day's paging run walks the leastLibraries and archives
    flow → how often an item from collection i and an item from collection j appear on the same retrieval slip, counted over a year of requests, dist → trolley travel distance between shelf range a and shelf range b, answer[i] → the shelf range holding collection i, cost → total trolley distance across that year of paging runs.
  • Assigning outbound blocks to classification tracks in a rail hump yardRail freight operations
    flow → cuts of cars that must be transferred between block i and block j while trains are built during a shift, dist → engine moves it costs to work between track a and track b, answer[i] → the classification track holding block i, cost → total engine moves per shift. Track length limits are not a qap term: screen out the block-and-track pairings that do not fit with rules first, then map the feasible remainder here — equal counts of blocks and tracks, padding with a zero-flow block if tracks are left over.

Measured at scale actually run

At 200 machines and 200 stations the two fields hold 40,000 work-in-progress flow entries and 40,000 station-to-station distances, 294 KB submitted once, and the answer is a full one-to-one layout. Optimality is not proven at this size - the label is heuristic - so recompute the travel cost with the free verify call.

Instance
200 variables · 40,000 flow entries · 40,000 distance entries
Answer
heuristic (labelled)
Engine time
26 ms (26 ms–26 ms, n=3)
Peak memory
3.0 MB
Request
294 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only qap --sizes target

How the encoding grows

The same two matrices at 45 machines and 45 stations hold 2,025 entries each — 4,050 numbers in one request, 990 unordered station pairs — and the layout cost sums 1,980 flow-by-distance products over one permutation out of 45! possible ones. The fields are identical to the 5-machine instance; only n moves. Each answer carries its own certainty label, which states whether the optimum was proven by exhaustion.

The encoding recipe (agent notes)

THE ENCODING RECIPE: qap takes a flow matrix (how much traffic moves between each pair of MACHINES) and a distance matrix (how far apart each pair of STATIONS is) and returns answer[i] = the station for machine i, minimizing total flow×distance. COMMON MISTAKES: (1) swapping the matrices — flow is between the things you place, distance between the places; mixing them up still runs but answers a different question; (2) not verifying — decode the permutation and recompute Σ flow[i][j]·dist[answer[i]][answer[j]]; it must equal cost; (3) missing that this is THE generic 'put chatty things close together' tool — GPU shard placement, microservice co-location, cross-dock door assignment, and keyboard layouts are all the same two matrices with different labels (see the AI-infrastructure and logistics examples); (4) symmetric ties — distinct permutations can reach the same cost when the matrices have symmetry, so store cost, not the permutation. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Place each machine at the station that minimizes total material handling.",
 "flow": [
  [
   0,
   5,
   2,
   4,
   1
  ],
  [
   5,
   0,
   3,
   0,
   2
  ],
  [
   2,
   3,
   0,
   0,
   0
  ],
  [
   4,
   0,
   0,
   0,
   5
  ],
  [
   1,
   2,
   0,
   5,
   0
  ]
 ],
 "dist": [
  [
   0,
   1,
   2,
   3,
   4
  ],
  [
   1,
   0,
   1,
   2,
   3
  ],
  [
   2,
   1,
   0,
   1,
   2
  ],
  [
   3,
   2,
   1,
   0,
   1
  ],
  [
   4,
   3,
   2,
   1,
   0
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "answer": [
  2,
  1,
  0,
  3,
  4
 ],
 "cost": 58,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example robotics_cell_layout --format json | hexstellar solve qap
curl -s https://api.hexstellar.com/api/v1/examples/robotics_cell_layout        # the full example over HTTP

🤖 Warehouse Fleet Path De-confliction

Robotics · command rules · effort flash · id: robotics_fleet_pathing

One boolean per (agent, cell, tick); excluding non-adjacent cell pairs across consecutive ticks leaves 'wait or move to a neighbour'.

A T-junction of floor cells — West, Center, East, and a North spur — carries two warehouse robots at once: robot A must travel West to East, robot B must come down from North and reach West, and every path runs through the single shared Center cell. HexStellar plans both trajectories jointly over four ticks: A crosses first (W, C, E, E) while B waits a tick on its spur (N, N, C, W). No cell ever holds two robots, every move is to an adjacent cell or a wait, and both goals are met — the fleet's next moves are conflict-free by construction, not by reactive dodging. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

Node robot*16 + tick*4 + cell (robots 0=A, 1=B; ticks 0-3; cells 0=West, 1=Center, 2=East, 3=North). answer[i] is 1 when that robot occupies that cell at that tick. violations is 0 when each robot is in exactly one cell per tick, no cell is shared, every step is adjacent-or-wait, and the start/goal pins hold.

Where this shows up

Warehouse robot fleets, AGV intersections, airport tug and taxiway sequencing, automated container yards — any multi-agent pathfinding loop where trajectories must be certified jointly, faster than the fleet moves.

The same encoding also solves 8

  • Meet-and-pass planning for two trains on a single-track branch line with passing loopsRail operations
    agents → trains; cells → track sections and passing loops; steps → block-occupancy periods; choose_one → a train holds exactly one section per period; same-cell exclusion → single-line block occupancy; non-adjacent-pair exclusion → a train may only advance to a connected section or hold; force_true → origin at the first period and destination at the last. On a plain single track, split each period in two so a mover holds both sections for one half-period — that is what forbids the head-on swap a pairwise rule cannot see.
  • Dispatching two elevator cars that share one shaft without letting them close on each otherBuilding systems
    agents → cars sharing a shaft; cells → floor bands; steps → dispatcher horizon steps; choose_one → a car is in exactly one band per step; same-cell exclusion → two cars cannot occupy one band; non-adjacent-pair exclusion → a car moves at most one band per step, which is its speed limit; force_true → each car's current band at the first step and its committed hall call at the last
  • Sequencing wafer lots through a cluster tool so the handler never double-books a chamberSemiconductor manufacturing
    agents → wafer lots; cells → process chambers, the aligner and the load-lock slots; steps → handler cycles; choose_one → a lot occupies exactly one position per cycle; same-cell exclusion → one wafer per chamber per cycle; non-adjacent-pair exclusion → a lot may only transfer to a position the handler physically reaches from its current one; force_true → the lot in the load lock at the first cycle and at the unload position at the last
  • Transit scheduling through one-way canal reaches with passing baysMaritime operations
    agents → vessels; cells → one-way reaches and passing bays; steps → transit windows; choose_one → a vessel is in exactly one reach per window; same-cell exclusion → a reach carries one vessel per window; non-adjacent-pair exclusion → a vessel advances to the next reach or holds in a bay; force_true → entry lock at the first window and exit lock at the last; half-window occupancy closes the head-on meet that pairwise rules alone cannot forbid
  • Camera and crane blocking for a live studio running orderBroadcast production
    agents → camera and crane rigs; cells → marked floor zones; steps → shots in the running order; choose_one → a rig stands in exactly one zone per shot; same-cell exclusion → two rigs cannot share a zone in one shot; non-adjacent-pair exclusion → a rig can only roll to a bordering zone between shots; force_true → the opening position and the scripted final mark
  • Building a slotframe schedule for a time-slotted industrial wireless meshIndustrial networking
    agents → flows; cells → radio links or channel offsets; steps → slots in the slotframe; choose_one → a flow transmits on exactly one link per slot; same-cell exclusion → two flows within interference range cannot take one channel-slot; non-adjacent-pair exclusion → a flow may only take a link incident to the node it currently sits at; force_true → source node at the first slot and gateway at the last
  • Charting a marching-band drill so no two performers land on the same field positionLive performance
    agents → performers; cells → field zones on the drill chart; steps → counts; choose_one → a performer stands in exactly one zone per count; same-cell exclusion → no zone holds two performers on a count; non-adjacent-pair exclusion → a performer may only step to a bordering zone between counts, which is their stride limit; force_true → the opening set and the closing form
  • De-conflicting haul trucks in a single-lane underground decline with cut-outsMining
    agents → haul trucks; cells → decline segments and cut-outs; steps → cycle steps; choose_one → a truck is in exactly one segment per step; same-cell exclusion → single-lane occupancy; non-adjacent-pair exclusion → a truck advances to a connected segment or holds; force_true → loading bay at the first step and tip point at the last. Passing-only-in-a-cut-out falls out of the topology itself; half-step occupancy forbids the head-on swap inside a plain segment.

Measured at scale actually run

The same time-expanded encoding at production size — 100,000 (robot, cell, tick) booleans in 10,000 robot-tick groups of ten cells, under 30,000 occupancy and motion rules, sent as one 1.6 MB request — comes back with the joint fleet plan's rule-violation count certified minimal and independently checked, so the whole horizon is cleared at once rather than one robot's path at a time.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape for 12 agents on a 150-cell floor over a 6-step rolling horizon is 12 × 150 × 6 = 10,800 booleans and 12 × 6 = 72 choose_one rules; shared-cell conflicts add 6 × 150 × C(12,2) = 59,400 exclusions, and the motion rules add one exclusion per agent, per consecutive step pair, per non-adjacent cell pair — the term that dominates the count, which is why the horizon is kept to a few steps and resubmitted as the fleet advances. The structure is byte-for-byte the same grammar as the 32-variable junction; a violations count of 0 certifies the whole joint plan rather than one agent's path.

The encoding recipe (agent notes)

THIS IS MULTI-AGENT PATHFINDING ON A TIME-EXPANDED GRAPH. THE ENCODING RECIPE: one boolean per (robot, cell, tick) plus choose_one per robot per tick — a robot is always somewhere. Collisions are mutual_exclusion between the two robots' booleans for the SAME (cell, tick). Motion physics is encoded by exclusion too: for every pair of cells that are NOT adjacent (and not equal), exclude (robot at c, tick t) with (robot at c', tick t+1) — what remains expressible is exactly 'wait or move to a neighbor'. Starts and goals are force_true. COMMON MISTAKES: (1) planning each robot separately and checking later — two individually optimal paths collide; the whole point is the JOINT solve; (2) the EDGE-SWAP hole — on a plain corridor, A moving u→v while B moves v→u passes every vertex constraint yet drives the robots through each other; pairwise rules cannot see a 4-literal conflict, so either use junction topologies where swaps are impossible (as here), halve the tick so a mover occupies both cells for one sub-tick, or switch to candidate-TRAJECTORY variables screened upstream (the satellite-maneuver example's pattern); (3) forgetting the wait action — goals force the last tick, and without 'stay' being legal the fastest robot has nowhere to idle; (4) effort scales with lattice density — even this toy junction is given up on at the lowest effort (an all-zero answer with many violations means 'raise effort', not 'infeasible'); it satisfies from medium up, and fleet×horizon grows fast, so certify a short rolling horizon every tick rather than a long one rarely. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Two robots, one junction: plan every robot's cell at every tick so the joint motion is collision-free by construction.",
 "n": 32,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1,
    2,
    3
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    4,
    5,
    6,
    7
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    8,
    9,
    10,
    11
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    12,
    13,
    14,
    15
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    16,
    17,
    18,
    19
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    20,
    21,
    22,
    23
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    24,
    25,
    26,
    27
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    28,
    29,
    30,
    31
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    16
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    4,
    20
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    8,
    24
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    12,
    28
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    1,
    17
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    5,
    21
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    9,
    25
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    13,
    29
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    2,
    18
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    6,
    22
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    10,
    26
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    14,
    30
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    3,
    19
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    7,
    23
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    11,
    27
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    15,
    31
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    6
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    7
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    2,
    4
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    2,
    7
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    3,
    4
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    3,
    6
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    4,
    10
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    4,
    11
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    6,
    8
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    6,
    11
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    7,
    8
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    7,
    10
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    8,
    14
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    8,
    15
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    10,
    12
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    10,
    15
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    11,
    12
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    11,
    14
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    16,
    22
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    16,
    23
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    18,
    20
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    18,
    23
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    19,
    20
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    19,
    22
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    20,
    26
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    20,
    27
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    22,
    24
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    22,
    27
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    23,
    24
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    23,
    26
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    24,
    30
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    24,
    31
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    26,
    28
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    26,
    31
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    27,
    28
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    27,
    30
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    0
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    14
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    19
   ]
  },
  {
   "type": "force_true",
   "nodes": [
    28
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example robotics_fleet_pathing --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/robotics_fleet_pathing        # the full example over HTTP

⌖ Deterministic Terrain Oracle

Robotics · command world · effort flash · id: world_terrain_oracle

A seeded terrain point returns a height and normal that can be finite-difference checked.

Evaluate the terrain height and normal at one deterministic grid location. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

re-query deterministically and finite-difference neighboring heights to check the normal

Where this shows up

Robotics, Gaming, Simulation

The same encoding also solves 3

  • Robot foothold queryRobotics
    foot location → x/z
  • Game-world level-of-detail probeGaming
    camera cell → x/z
  • Synthetic terrain regressionSimulation
    test coordinate → x/z

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Evaluate the terrain height and normal at one deterministic grid location.",
 "op": "terrain",
 "x": 3,
 "z": 4
}

Expected (engine-verified)

expected.json
{
 "answer": [
  "HEIGHT 3.050637906",
  "NORMAL -0.338595932 0.940490476 0.028817684"
 ],
 "op": "terrain",
 "certainty": "operation result (optimality not applicable; no independent proof checked)"
}

Run it

terminal
hexstellar example world_terrain_oracle --format json | hexstellar solve world
curl -s https://api.hexstellar.com/api/v1/examples/world_terrain_oracle        # the full example over HTTP

Scheduling

🗓️ Facility Session Scheduling

Scheduling · command rules · effort flash · id: facility_session_scheduling

One variable per (item, slot): together is identical per slot, apart is mutual_exclusion per slot — different only works at 2 slots.

Four sessions must each be assigned to one of two rooms, with no room holding more than three. Sessions 0 and 1 share a team, so they must be in the same room. Sessions 2 and 3 clash and must be in different rooms. HexStellar returns a room assignment that satisfies every rule. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is one-hot per session: variable (session*2 + room) is 1 for the chosen room. violations is 0 when the capacity, together, and apart rules all hold.

Where this shows up

Operating-room and clinic scheduling, classroom and exam-hall allocation, meeting-room booking, shift co-location.

The same encoding also solves 7

  • Berth allocation for a tide window where two vessels must not draw on the same shore cranePort operations
    sessions → vessels to be worked, rooms → berths, choose_one → each vessel is worked at exactly one berth, capacity_limit k → vessels a berth can take in the window, identical paired per berth → two barges of one convoy discharged at the same berth, must-split → the two vessels that both need the single SHORE crane fixed to one berth (a mobile crane that moves between berths is a time conflict this encoding has no term for), written as one mutual_exclusion per berth beyond two berths (different per berth at exactly two), violations 0 → a berthing plan that breaks no rule
  • Assigning scenes to sound stages when one standing set cannot be struckFilm and television production
    sessions → scenes to shoot, rooms → the two sound stages, choose_one → each scene is shot on exactly one stage, capacity_limit k → setups a stage can hold in the block, identical paired per stage → two scenes that reuse one standing set, different paired per stage → two scenes whose lighting rigs conflict, violations 0 → a shooting plan that breaks no rule
  • Placing exam sections into halls so a paper and its resit never share a hallHigher education
    sessions → exam sections, rooms → halls, choose_one → each section sits in exactly one hall, capacity_limit k → sections a hall can take as a COUNT of sections, faithful only where sections are equal-sized (a hall's seat ceiling against unequal section sizes is a continuous quantity, not a count, and belongs in a milp objective term rather than capacity_limit), identical paired per hall → two sections of one course kept together for a single invigilator briefing, must-split → a paper and its resit version, as one mutual_exclusion per hall beyond two halls (different per hall at exactly two), violations 0 → a seating plan that breaks no rule
  • Splitting product campaigns across packaging lines to keep an allergen product off the shared lineFood and beverage manufacturing
    sessions → product campaigns, rooms → the two packaging lines, choose_one → each campaign runs on exactly one line, capacity_limit k → campaigns a line takes in the period, identical paired per line → two same-formulation campaigns kept on one line to avoid a changeover, different paired per line → an allergen-bearing product and an allergen-free product, violations 0 → a run plan with no cross-contact path
  • Assigning simultaneous emergency drills to training groundsEmergency services
    sessions → drills, rooms → the two training grounds, choose_one → each drill runs at exactly one ground, capacity_limit k → drills a ground can host, identical paired per ground → the joint fire-and-EMS pair that must drill together, different paired per ground → two live-fire exercises, violations 0 → a drill schedule that breaks no safety rule
  • Assigning product categories to display islands with a cross-merchandising pair and two anchorsRetail merchandising
    sessions → categories to display, rooms → display islands, choose_one → each category sits on exactly one island, capacity_limit k → categories an island holds, identical paired per island → a cross-merchandising pair such as grills and charcoal, must-split → the two anchor categories, as one mutual_exclusion per island beyond two islands (different per island at exactly two), violations 0 → a floor plan that breaks no merchandising rule
  • Placing language queues across two sites so a disaster-recovery pair is never co-locatedContact centre operations
    sessions → queues, rooms → the two sites, choose_one → each queue is staffed at exactly one site, capacity_limit k → queues a site can staff as a COUNT of queues, faithful only where queues carry comparable volume (a site's agent or seat ceiling against unequal queue sizes is a continuous quantity, not a count, and belongs in a milp objective term rather than capacity_limit), identical paired per site → two queues sharing one bilingual team, different paired per site → a primary queue and its recovery queue, violations 0 → a staffing map that keeps every recovery pair separated

Measured at scale actually run

The same one-hot encoding at 100,000 (session, room) variables — 10,000 sessions over 10 rooms — under 30,000 choose-one, per-room capacity, must-share and must-split rules yields a room assignment whose violation count is certified as the minimum, all of it submitted as a single 1,602 KB request.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

At 500 sessions and 12 rooms the same encoding is 6,000 binary variables, 500 choose_one rules, 12 capacity_limit rules and 12 rules per related pair, so 200 must-share and 150 must-split pairs add 4,200 rules — 4,712 in all. One structural note as the room count grows: a must-share pair stays identical paired per room, while a must-split pair is one mutual_exclusion per room; different per room states the same thing only when there are exactly 2 rooms.

The encoding recipe (agent notes)

'MUST BE TOGETHER' vs 'MUST BE APART' WITH ONE-HOT ROOMS: each session gets one variable per room (session*R + room) plus choose_one. Two sessions in the SAME room = identical on their matching room variables (e.g. identical on [s0_room0, s1_room0] AND [s0_room1, s1_room1]). Two sessions in DIFFERENT rooms = different on the matching room variables. COMMON MISTAKES: (1) setting a capacity so tight that 'together' can't fit — if a two-session team must share a room of capacity 2, and a third session is forced there too, it's infeasible; loosen capacity or add rooms; (2) applying identical/different to only one of the room variables — with R rooms you generally pair them per room; (3) mixing up identical (same value) with requires (implication). CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Assign sessions to rooms — keep the shared-team pair together, the clashing pair apart.",
 "n": 8,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    2,
    3
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    4,
    5
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    6,
    7
   ]
  },
  {
   "type": "capacity_limit",
   "k": 3,
   "nodes": [
    0,
    2,
    4,
    6
   ]
  },
  {
   "type": "capacity_limit",
   "k": 3,
   "nodes": [
    1,
    3,
    5,
    7
   ]
  },
  {
   "type": "identical",
   "nodes": [
    0,
    2
   ]
  },
  {
   "type": "identical",
   "nodes": [
    1,
    3
   ]
  },
  {
   "type": "different",
   "nodes": [
    4,
    6
   ]
  },
  {
   "type": "different",
   "nodes": [
    5,
    7
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example facility_session_scheduling --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/facility_session_scheduling        # the full example over HTTP

Scientific Computing

🧪 Numerical Scheme Ensemble Cover

Scientific Computing · command rules · effort flash · id: hpc_solver_ensemble

choose_exactly k=1 per requirement, listing only the bundles that serve it; the exclusions go on the covering sets, not the elements.

A large simulation campaign must pick numerical schemes so that each of five stability regimes is handled by exactly one selected scheme. Seven candidates overlap: two specialist pairs, two single-regime specialists, and one monolithic scheme covering four regimes at once. The trap is that coverage alone is not enough — scheme pairings carry numerical incompatibilities: the two obvious specialist pairs cannot co-run (timestep mismatch), and the monolithic scheme cannot share the ensemble with either remaining specialist. HexStellar returns a selection that satisfies BOTH structures simultaneously: schemes {2, 3, 4} — the cross-cutting specialists plus one regime-4 solver — covering every regime exactly once with zero conflicts. This mixes Exact Cover with conflict edges between the covering sets, which is how real formulation problems actually arrive: two clean textbook shapes tangled together. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is 1 when scheme i joins the ensemble. violations is 0 when every stability regime is covered by exactly one selected scheme AND no incompatible pair of schemes is selected together. Two valid ensembles exist ({2,3,4} and {3,4,5}) — test the invariant.

Where this shows up

Numerical scheme and solver selection for multi-physics campaigns, force-field pack selection in molecular dynamics (each interaction type covered once, incompatible parameterizations excluded), instrument-mode selection on shared observatories, compiler-pass or feature-flag sets where coverage obligations and pairwise incompatibilities coexist.

The same encoding also solves 7

  • Crew pairing where every flight leg must be flown by exactly one published pairingAirlines
    schemes → candidate crew pairings, stability regimes → flight legs, choose_exactly k=1 per regime → each leg flown by exactly one selected pairing (a second pairing on the same leg is a paid duplicate, none is an uncrewed leg), mutual_exclusion → two pairings that need the same single qualified captain or the same overnight bed
  • Placing a reinsurance programme so every risk layer is ceded to exactly one treatyInsurance
    schemes → candidate treaties, each covering a band of layers, stability regimes → risk layers, choose_exactly k=1 → a layer is ceded once and only once (a gap is retained risk, an overlap is paid twice), mutual_exclusion → two treaties that cannot both be bound because they draw on one reinsurer's aggregate limit
  • Assay panel selection where every biomarker is measured on exactly one panelDiagnostics
    schemes → candidate assay panels, stability regimes → biomarkers that must be measured, choose_exactly k=1 → each biomarker measured once (a repeat consumes the sample twice and adds a batch effect), mutual_exclusion → two panels whose fluorophores share a detection channel and cannot run in one instrument pass
  • Multiplex primer pooling where every target region is amplified by exactly one poolGenomics
    schemes → candidate primer pools, stability regimes → target regions to amplify, choose_exactly k=1 → each region amplified by exactly one pool, mutual_exclusion → two pools holding primers that bind each other and therefore cannot share a reaction
  • Tooling-package selection where every part feature is produced by exactly one packageManufacturing
    schemes → candidate tooling packages, stability regimes → part features to be produced, choose_exactly k=1 → each feature produced by exactly one package (two packages on one feature split tolerance ownership), mutual_exclusion → two packages that need the same fixture mount and cannot be installed together
  • Buying a security stack where every control requirement is met by exactly one productIT Procurement
    schemes → candidate products, each covering several controls, stability regimes → the control requirements in the framework, choose_exactly k=1 → each control owned by exactly one product (two owners means neither is accountable at audit), mutual_exclusion → two endpoint agents that cannot be installed on the same host
  • Media plan where every audience segment is reached by exactly one campaign flightAdvertising
    schemes → candidate campaign flights, each reaching a set of segments, stability regimes → audience segments, choose_exactly k=1 → each segment reached exactly once (a second reach breaks the frequency cap), mutual_exclusion → two flights from competing brands that may not run in the same break

Measured at scale actually run

The same doubled structure at 100,000 candidate schemes — 10,000 stability regimes each to be covered by exactly one of ten candidates — with 30,000 coverage and incompatibility rules in a single 1.6 MB request returns an ensemble whose rule-violation count is certified minimal and independently checked, both rule families answered in the one request rather than covered first and conflict-checked afterwards.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape at 3,000 candidate bundles over 1,200 requirements is 3,000 booleans and 1,200 choose_exactly k=1 rules — each listing only the bundles that serve that one requirement — plus one mutual_exclusion per recorded incompatible bundle pair, bounded above by the 4,498,500 pairs a fully hostile portfolio would have. Only the counts change: both rule families still travel in one request, because a cover chosen first and conflict-checked afterwards is a different and weaker problem. Exactly-once is choose_exactly k=1; at-least-once with per-bundle costs is the cover command; the cheapest exact partition puts per-bundle prices in this command's optional linear objective. Certification is reported per answer and is not decided by portfolio size: a 100,000-boolean rule set carrying 30,000 rules has come back certified, so read the label the answer carries rather than assuming a bigger portfolio must be a labelled heuristic.

The encoding recipe (agent notes)

THE LESSON: REAL PROBLEMS MIX SHAPES. This instance is Exact Cover (choose_exactly k=1 per regime over the schemes that handle it) PLUS Independent-Set-style conflict edges (mutual_exclusion between incompatible schemes) — and the two structures interact: the exclusions eliminate some covers, so neither structure can be solved first and patched later; they must be satisfied in ONE solve. Here the two most 'natural' answers — the matched specialist pair and the monolithic scheme — are both eliminated by conflicts, and the surviving cover crosses the specialist boundaries. COMMON MISTAKES: (1) solving the cover first, then checking conflicts — you will pick an eliminated cover and enter a rewrite loop; state both rule families and let the engine navigate the intersection; (2) attaching the exclusions to REGIMES instead of SCHEME PAIRS — incompatibility is between the covering sets, not between the elements being covered; (3) the usual exact-cover traps still apply (capacity_limit would allow uncovered regimes; constraints live on the elements, one per regime); (4) if the conflicts eliminate EVERY cover, violations comes back >0 — read that as a formulation diagnosis (your scheme portfolio is inconsistent), and drop the least-critical conflict or add a candidate scheme rather than blaming the engine. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Cover every stability regime exactly once with schemes that are also mutually compatible — coverage and conflicts in one solve.",
 "n": 7,
 "constraints": [
  {
   "type": "choose_exactly",
   "k": 1,
   "nodes": [
    0,
    3,
    6
   ]
  },
  {
   "type": "choose_exactly",
   "k": 1,
   "nodes": [
    0,
    4,
    6
   ]
  },
  {
   "type": "choose_exactly",
   "k": 1,
   "nodes": [
    1,
    3,
    6
   ]
  },
  {
   "type": "choose_exactly",
   "k": 1,
   "nodes": [
    1,
    4,
    6
   ]
  },
  {
   "type": "choose_exactly",
   "k": 1,
   "nodes": [
    2,
    5
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    1
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    6,
    2
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    6,
    5
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example hpc_solver_ensemble --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/hpc_solver_ensemble        # the full example over HTTP

ƒ Golden-Ratio Relation Witness

Scientific Computing · command relation · effort flash · id: math_golden_ratio_relation

A high-precision constant yields a residual-checked polynomial witness, not a theorem.

Find and independently residual-check the golden ratio polynomial relation. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

evaluate the emitted integer polynomial at higher precision

Where this shows up

Experimental mathematics, Numerical computing, Scientific computing

The same encoding also solves 3

  • Minimal-polynomial discoveryExperimental mathematics
    decimal constant → constants
  • Identity auditNumerical computing
    measured constants → constants
  • Symbolic-regression seedScientific computing
    candidate values → constants

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Find and independently residual-check the golden ratio polynomial relation.",
 "minpoly": 2,
 "height": 10,
 "constants": [
  "1.61803398874989484820458683436"
 ]
}

Expected (engine-verified)

expected.json
{
 "answer": {
  "relation": "found",
  "coeffs": [
   1,
   1,
   -1
  ],
  "polynomial": "x^2 - x - 1"
 },
 "residual": "2.408e-30",
 "agree_digits": "29",
 "certainty": "certified witness (independently checked; optimality unknown)"
}

Run it

terminal
hexstellar example math_golden_ratio_relation --format json | hexstellar solve relation
curl -s https://api.hexstellar.com/api/v1/examples/math_golden_ratio_relation        # the full example over HTTP

√ High-Precision Square Root

Scientific Computing · command precision · effort flash · id: math_sqrt2_precision

The returned digits are checked by squaring at higher precision.

Compute the square root of two to 31 significant digits. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

square the returned decimal in an independent higher-precision library and bound the residual

Where this shows up

Metrology, Software testing, Scientific computing

The same encoding also solves 3

  • Reference constant generationMetrology
    constant request → op
  • Numerical regression oracleSoftware testing
    known operand → x
  • Precision-loss diagnosisScientific computing
    operation and digits → op/sig

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Compute the square root of two to 31 significant digits.",
 "prec": "dd",
 "op": "sqrt",
 "x": "2",
 "sig": 31
}

Expected (engine-verified)

expected.json
{
 "answer": "1.414213562373095048801688724209e0",
 "prec": "dd",
 "op": "sqrt",
 "sig": 31,
 "certainty": "operation result (optimality not applicable; no independent proof checked)"
}

Run it

terminal
hexstellar example math_sqrt2_precision --format json | hexstellar solve precision
curl -s https://api.hexstellar.com/api/v1/examples/math_sqrt2_precision        # the full example over HTTP

2ⁿ 65,536-Variable Planted Floor

Scientific Computing · command quantum-scale · effort flash · id: scale_planted_65536

A 2^65536 space reaches a construction-known floor without claiming arbitrary NP-hardness.

Evaluate a planted 65,536-variable scale ruler with a known construction floor. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

compare answer, planted_target and residual; do not generalize to arbitrary inputs

Where this shows up

HPC, Infrastructure, Audit

The same encoding also solves 3

  • Scale-path validationHPC
    synthetic dimension → n
  • Serialization stressInfrastructure
    generated variables → n
  • Receipt reproducibilityAudit
    seeded construction → receipt

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Evaluate a planted 65,536-variable scale ruler with a known construction floor.",
 "n": 65536,
 "seed": 20260828,
 "degree": 3
}

Expected (engine-verified)

expected.json
{
 "answer": -163208,
 "planted_target": -163208,
 "residual": 0,
 "dimensions": 65536,
 "space": "2^65536 (a 19729-digit number)",
 "quality": "floor-exact",
 "certainty": "certified optimum (independently checked)"
}

Run it

terminal
hexstellar example scale_planted_65536 --format json | hexstellar solve quantum-scale
curl -s https://api.hexstellar.com/api/v1/examples/scale_planted_65536        # the full example over HTTP

∿ Enumerable Distribution Sample

Scientific Computing · command sample · effort flash · id: science_enumerable_sampling

An empirical distribution is checked as a distribution, never mislabeled as an optimum.

Draw a reproducible empirical sample from a six-variable coupled distribution. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

check counts sum, probabilities normalize, energies recompute and compare toy frequencies with exact enumeration

Where this shows up

Risk, Engineering, Science

The same encoding also solves 3

  • Scenario generationRisk
    binary scenarios → samples
  • Configuration diversityEngineering
    coupled configurations → samples
  • Uncertainty explorationScience
    states and weights → distribution

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Draw a reproducible empirical sample from a six-variable coupled distribution.",
 "n": 6,
 "field": {
  "0": -1
 },
 "couple": [
  [
   0,
   1,
   2
  ],
  [
   1,
   2,
   2
  ],
  [
   2,
   3,
   2
  ],
  [
   3,
   4,
   2
  ],
  [
   4,
   5,
   2
  ],
  [
   5,
   0,
   2
  ]
 ],
 "num_samples": 500,
 "temp": 2.0
}

Expected (engine-verified)

expected.json
{
 "num_samples": 500,
 "kind": "samples (draws from the world's low-energy distribution)",
 "certainty": "empirical distribution (a sample, not a single proven optimum — verify)"
}

Run it

terminal
hexstellar example science_enumerable_sampling --format json | hexstellar solve sample
curl -s https://api.hexstellar.com/api/v1/examples/science_enumerable_sampling        # the full example over HTTP

≈ Planted Dominant Frequency

Scientific Computing · command frequency · effort flash · id: science_planted_frequency

A signal with a planted period returns the exact dominant bin.

Identify the known dominant frequency in a periodic sampled signal. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

independent DFT power spectrum

Where this shows up

Mechanical engineering, Finance, Hardware

The same encoding also solves 3

  • Rotor vibration diagnosisMechanical engineering
    sensor samples → signal
  • Seasonality detectionFinance
    returns by interval → signal
  • Clock-jitter inspectionHardware
    timing residuals → signal

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Identify the known dominant frequency in a periodic sampled signal.",
 "signal": [
  1.0,
  0.0,
  -1.0,
  0.0,
  1.0,
  0.0,
  -1.0,
  0.0
 ]
}

Expected (engine-verified)

expected.json
{
 "answer": {
  "dominant_bin": 2,
  "cycles_per_sample": 0.25,
  "period_samples": 4.0
 },
 "certainty": "operation result (optimality not applicable; no independent proof checked)"
}

Run it

terminal
hexstellar example science_planted_frequency --format json | hexstellar solve frequency
curl -s https://api.hexstellar.com/api/v1/examples/science_planted_frequency        # the full example over HTTP

Security

🛡️ Zero-Trust Segment Assignment

Security · command rules · effort flash · id: cyber_zero_trust

A policy is one rule per segment on the pair's same-segment variables: identical for must-share, mutual_exclusion for must-separate.

An enterprise has a pile of human-written network policies: some workloads must be able to talk (so they share a segment), some must never share a segment (compliance isolation), and each segment has a size budget. HexStellar assigns every workload class to a network segment so every policy holds at once — here six workload classes into two segments with zero violations. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is one-hot per workload class: variable (class*2 + segment) is 1 for the chosen segment. violations is 0 when every together/apart/size policy holds.

Where this shows up

Zero-trust microsegmentation, VLAN/security-group assignment, PCI/tenant isolation zoning, data-residency partitioning — turning a policy document into an enforceable segmentation.

The same encoding also solves 7

  • Hazmat storage bay assignment where incompatible chemical classes may not share a bayChemical logistics
    workload classes → chemical classes awaiting storage, segments → storage bays, choose_one → each class is stored in exactly one bay, capacity_limit k → how many classes one bay may hold as a COUNT of classes (a weight or volume ceiling is a continuous quantity, and no rule family states a weighted ceiling — carry it as a cost term in a milp objective, which takes no constraint list, or discretise it into count buckets here), identical paired per bay → two classes that must sit under one containment plan, mutual_exclusion paired per bay → an incompatible pair such as an oxidiser and an organic peroxide, violations 0 → a storage plan that breaks no separation rule
  • Placing ad creatives into break pods with competitive brand separationAdvertising operations
    workload classes → creatives to air, segments → break pods in the schedule, choose_one → each creative airs in exactly one pod, capacity_limit k → spots available in a pod, identical paired per pod → the two halves of a split creative that must air in the same pod, mutual_exclusion paired per pod → two competing brands that may never share a pod, violations 0 → a schedule no advertiser contract objects to
  • Assigning process steps to chambers so metal-bearing and photoresist steps never share oneSemiconductor manufacturing
    workload classes → process steps in the campaign, segments → chambers, choose_one → each step runs in exactly one chamber, capacity_limit k → steps a chamber may host in the campaign, identical paired per chamber → two steps that must share a chamber for run-to-run matching, mutual_exclusion paired per chamber → a contamination pair such as metal etch with lithography, violations 0 → a chamber allocation with no contamination path
  • Assigning client matters to practice teams under conflict-of-interest wallsLegal services
    workload classes → client matters, segments → practice teams, choose_one → each matter has exactly one owning team, capacity_limit k → matters a team may carry, identical paired per team → two matters of one corporate group that must sit with the same team, mutual_exclusion paired per team → two matters on opposite sides of a dispute, violations 0 → an allocation that respects every wall
  • Penning livestock groups so different disease-status groups never share a penLivestock agriculture
    workload classes → animal groups, segments → pens, choose_one → each group occupies exactly one pen, capacity_limit k → groups per pen as a COUNT of groups (head counts and feed weights are continuous quantities — no rule family states a weighted ceiling, so carry one as a cost term in a milp objective, which takes no constraint list), identical paired per pen → two groups on one treatment protocol, mutual_exclusion paired per pen → a seropositive group with a naive group, violations 0 → a penning plan with no cross-exposure
  • Drawing clubs into competition groups with stadium-sharing and travel-cluster rulesProfessional sports
    workload classes → clubs, segments → groups in the draw, choose_one → each club is drawn into exactly one group, choose_exactly k per group → exactly k clubs in every group, which is what a draw requires (capacity_limit is at-most-k and can leave a group short unless the club count exactly fills the groups), identical paired per group → two clubs of one travel cluster placed together, mutual_exclusion paired per group → two clubs sharing a stadium whose home dates would collide, plus one more per group for each association-protection pair that may not be drawn together, violations 0 → a draw that breaks no drawing rule
  • Assigning trial cohorts to investigator sites so blinded arms never share a siteClinical research
    workload classes → cohorts to be enrolled, segments → investigator sites, choose_one → each cohort runs at exactly one site, capacity_limit k → cohorts a site may run, identical paired per site → two cohorts that must share one specialised imaging device and therefore one site, mutual_exclusion paired per site → two arms whose site staff overlap would unblind them if co-located (blinded arms do normally share a site; the rule is about the staff overlap, not the blind itself), violations 0 → a site map that keeps every unblinding pair apart

Measured at scale actually run

Measured at 100,000 class-in-segment variables under 30,000 declared must-share, keep-apart and segment-size rules, the same policy encoding returned a segmentation from a 1,602 KB request inside 16,588 KB of memory, and the number of policies the assignment breaks is certified minimal and independently checked.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

At 300 workload classes and 8 segments the identical encoding is 2,400 binary variables, 300 choose_one rules (one per class), 8 capacity_limit rules (one per segment) and 8 pairwise rules per policy, so 120 must-share plus 400 must-keep-apart policies add 4,160 rules — 4,468 rules submitted as one request, with the rule types unchanged. A returned 0 violations certifies the whole policy set holds together; a nonzero count is the number of declared rules the returned assignment breaks, recomputable from the problem by arithmetic.

The encoding recipe (agent notes)

THE THESIS: your business rules ARE an optimization problem. 'Finance and Ledger must talk' → identical on their same-segment variables (same segment). 'PCI must never share a segment with Analytics' → mutual_exclusion per segment on their same-segment variables. 'This workload lives in exactly one segment' → choose_one over its per-segment variables. 'A segment holds at most k workloads' → capacity_limit. The domain is security; the encoding is identical to container loading, VM placement, and room scheduling — the mountain underneath doesn't change. COMMON MISTAKES: (1) swapping identical (must be TOGETHER) and mutual_exclusion (must be APART); (2) applying the rule to only one segment's variable — with S segments you pair them per segment; (3) trying to express 'at least one gateway of a set must be up' or 'a segment's total bandwidth ≤ B' — rules does exactly-one and at-most-COUNT, not at-least-k or weighted budgets; those need optimize. WHAT TO SHOW A SKEPTIC: change the story to hospitals, factories, or datacenters and the same three rule types still model it. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Compile network policies into a segmentation that keeps the wrong workloads apart.",
 "n": 12,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    2,
    3
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    4,
    5
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    6,
    7
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    8,
    9
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    10,
    11
   ]
  },
  {
   "type": "capacity_limit",
   "k": 4,
   "nodes": [
    0,
    2,
    4,
    6,
    8,
    10
   ]
  },
  {
   "type": "capacity_limit",
   "k": 4,
   "nodes": [
    1,
    3,
    5,
    7,
    9,
    11
   ]
  },
  {
   "type": "identical",
   "nodes": [
    0,
    2
   ]
  },
  {
   "type": "identical",
   "nodes": [
    1,
    3
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    4,
    6
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    5,
    7
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    8,
    10
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    9,
    11
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example cyber_zero_trust --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/cyber_zero_trust        # the full example over HTTP

⌁ Protected Payload Envelope

Security · command protect · effort flash · id: integrity_protect_payload

The digest is a public integrity witness for an exact future recovery.

Protect a compact routing instruction and emit its integrity witness. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

recover the emitted object and compare byte-for-byte plus digest

Where this shows up

HPC, IoT, AI infrastructure

The same encoding also solves 3

  • Checkpoint protectionHPC
    checkpoint bytes → payload
  • Telemetry packet protectionIoT
    packet bytes → payload
  • Model-state transportAI infrastructure
    state bytes → payload

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Protect a compact routing instruction and emit its integrity witness.",
 "text": "Route A->B: cost 42, cut 7"
}

Expected (engine-verified)

expected.json
{
 "op": "protect",
 "digest": "e3c9069dcbf015f02d886c00d6dc3c52141c742b7bdeb5af5eecc878d72281fe",
 "n_msg_bytes": 26,
 "n_data_bits": 208,
 "n_protected_bits": 416,
 "storage_bytes": 52,
 "certainty": "verified operation (independent integrity witness reproduced)"
}

Run it

terminal
hexstellar example integrity_protect_payload --format json | hexstellar solve protect
curl -s https://api.hexstellar.com/api/v1/examples/integrity_protect_payload        # the full example over HTTP

↺ Byte-Exact Recovery

Security · command recover · effort flash · id: integrity_recover_payload

Recovery succeeds only when the restored bytes reproduce the sealed digest.

Recover a one-byte protected message and verify it against its digest. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

hash the returned bytes independently; tamper beyond the budget must refuse

Where this shows up

HPC, Networking, Storage

The same encoding also solves 3

  • Corrupted checkpoint restorationHPC
    protected bytes → symbols
  • Noisy link recoveryNetworking
    received symbols → symbols
  • Archive integrity restorationStorage
    stored protected object → request

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Recover a one-byte protected message and verify it against its digest.",
 "symbols": [
  1,
  0,
  0,
  1,
  2,
  1,
  0,
  2
 ],
 "digest": "559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd",
 "n_msg_bytes": 1,
 "n_data_bits": 8,
 "n_protected_bits": 16
}

Expected (engine-verified)

expected.json
{
 "op": "recover",
 "recovered": true,
 "message": "41",
 "text": "A",
 "certainty": "verified operation (independent integrity witness reproduced)"
}

Run it

terminal
hexstellar example integrity_recover_payload --format json | hexstellar solve recover
curl -s https://api.hexstellar.com/api/v1/examples/integrity_recover_payload        # the full example over HTTP

ℤ Unimodular Lattice Reduction

Security · command reduce · effort flash · id: math_unimodular_reduction

The output must span the identical integer lattice and satisfy reduction checks.

Reduce a two-dimensional integer lattice basis without claiming the shortest vector. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

check equal lattice determinant/index, unimodular relation and reduction inequalities

Where this shows up

Cryptography, Mathematics, Data science

The same encoding also solves 3

  • Integer-lattice conditioningCryptography
    basis vectors → basis
  • Diophantine preprocessingMathematics
    coefficient lattice → basis
  • Integer feature decorrelationData science
    integer vectors → basis

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Reduce a two-dimensional integer lattice basis without claiming the shortest vector.",
 "basis": [
  [
   201,
   37
  ],
  [
   1648,
   297
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "answer": [
  [
   1,
   32
  ],
  [
   40,
   1
  ]
 ],
 "shortest": {
  "index": 0,
  "norm2_str": "1025"
 },
 "certainty": "reduced (same lattice; b_1 provably short, not proven minimal)"
}

Run it

terminal
hexstellar example math_unimodular_reduction --format json | hexstellar solve reduce
curl -s https://api.hexstellar.com/api/v1/examples/math_unimodular_reduction        # the full example over HTTP

📹 Dual-Watcher Camera Plan

Security · command rules · effort flash · id: security_dual_watch

The quota sits on each covered element's candidate group, not on the devices; at-most-2 is satisfied by zero watchers, exactly-2 is not.

Four cameras can each see into some of three zones: zone A is visible to cameras 0, 1, 2; zone B to 1, 2, 3; zone C only to 0 and 3. The requirement is exact double-coverage: every zone watched by exactly TWO enabled cameras — two for fault tolerance, and not three, because extra streams cost bandwidth and review time. Because the cameras are shared between zones, the quotas couple: zone C immediately forces cameras 0 AND 3 on (it has only two candidates), and then zones A and B each need exactly one of the shared pair {1, 2}. HexStellar returns a valid plan (cameras 0, 1, 3); brute force confirms exactly two valid plans exist. This is Exact Multicover — NP-complete in general — expressed as one choose_exactly k=2 per zone. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is 1 when camera i is enabled. violations is 0 when every zone is watched by exactly two enabled cameras. Two valid plans exist ({0,1,3} and {0,2,3}) — test the invariant, not the plan.

Where this shows up

Camera and guard coverage with uniform redundancy, dual-sensor safety interlocks (two independent smoke detectors per compartment), double-signing policies (every release approved by exactly two owners), N+1-exact power feeds, dual-witness audit requirements — anywhere 'exactly two watchers' is the contract.

The same encoding also solves 7

  • Powering flight-control sensor units so every measured parameter is read by exactly two unitsAerospace avionics
    cameras → sensor units that can be powered, zones → measured parameters, a zone's candidate group → the units wired to that parameter, choose_exactly k → the redundancy level the architecture contracts for (k=2 for a dual-channel design, k=3 where a voting triplex is required — k is a parameter, not fixed at two), violations 0 → every parameter read by exactly k live units; where the standard is written as a floor of k rather than exactly k, that regime is the companion command cover with min_cover k
  • Rostering duty officers so each account has exactly two authorised release approvers on shiftBanking compliance
    cameras → officers placed on shift, zones → accounts needing release authority, candidate group → the officers holding that account's mandate, choose_exactly k=2 → a mandate written as EXACTLY two approvers, which also bans a padded third, violations 0 → every account carrying exactly its pair; the four-eyes rule as usually written is a FLOOR of two, and that regime is the companion command cover with min_cover 2, not choose_exactly
  • Choosing which axle-counter units to commission so each interlocking area is sensed by exactly twoRail signalling
    cameras → axle-counter units, zones → interlocking areas, candidate group → the units whose detection section reaches that area, choose_exactly k=2 → the two-out-of-two detection standard, violations 0 → every area doubly sensed and none triple-counted
  • Selecting gas-detector positions so every compartment is monitored by exactly two independent headsOffshore energy safety
    cameras → detector positions that can be fitted, zones → compartments, candidate group → the positions whose sensing radius covers that compartment, choose_exactly k=2 → the independent-pair requirement, violations 0 → every compartment paired; where the standard is written as a floor of two rather than exactly two, use cover with min_cover 2
  • Energising branch circuits so every rack is fed by exactly two live feedsData centre infrastructure
    cameras → branch circuits that can be energised, zones → racks, candidate group → the circuits reaching that rack, choose_exactly k=2 → the 2N feed contract, where a third feed is stranded capacity, violations 0 → every rack on exactly two feeds; unequal circuit costs go in the optional linear weights on the same variables
  • Keeping exactly two sectors active per coverage area during a low-demand windowTelecommunications
    cameras → sectors that stay energised, zones → coverage areas, candidate group → the sectors whose footprint includes that area, choose_exactly k=2 → one serving sector plus one handover neighbour, violations 0 → no area left on a single sector and none carrying a third that only adds interference
  • Designating exactly two market makers per listed instrument from the firms qualified to quote itCapital markets infrastructure
    cameras → market-making firms accepting a designation, zones → listed instruments, candidate group → the firms qualified in that instrument, choose_exactly k=2 → the exchange's two-designated-maker rule, violations 0 → every instrument carrying exactly two designated firms

Measured at scale actually run

The same exact-quota encoding has been measured with 100,000 enableable-device variables and 30,000 declared quota rules in a 1,602 KB request, and the returned coverage plan carries a certified-minimal, independently checked count of quota rules left unmet — which is what separates a plan you can sign from one you must re-count by hand.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

At 4,000 candidate devices and 1,200 covered elements the encoding is 4,000 binary variables and 1,200 choose_exactly rules, one per element listing only that element's own candidates — at an average of 6 candidates per element that is 7,200 index references and zero rules between elements, since all of the coupling comes from candidates that appear in several groups. A returned 0 violations means every quota is met exactly; a nonzero count is how many quotas are off. If an element's requirement is a floor of k rather than exactly k, that regime is the companion command cover with min_cover, not choose_exactly.

The encoding recipe (agent notes)

THE COVERAGE QUARTET, COMPLETED. Hard rules now express four coverage regimes, and choosing the right one is the lesson: exactly-ONE per element = exact cover (the kit-partition example); exactly-TWO (or k) per element = THIS example, choose_exactly k=2 on each element's candidate group; at-LEAST-one-of-a-pair = the different-complement gadget (the hub-coverage example); at-MOST-k = capacity_limit. General at-least-k for k≥2 remains inexpressible — but note that when supply is tight, exactly-k IS the honest requirement, and it is native. COMMON MISTAKES: (1) reaching for an at-least-2 quota when the contract really is exactly-2 — over-coverage is a cost (bandwidth, alarm fatigue, double-signing overhead), and choose_exactly bans it for free; (2) putting one global cardinality on all cameras instead of one quota PER ZONE — the constraint lives on the covered elements, and the shared cameras are what couple the quotas (zone C's tightness cascades into A and B, so per-zone greedy fails); (3) capacity_limit k=2 instead of choose_exactly — at-most-2 is satisfied by watching a zone with ZERO cameras; (4) infeasibility diagnosis: if quotas conflict (violations>0), a zone's candidate list is too thin — add cameras to that zone's group rather than relaxing the quota globally. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Enable cameras so each of three zones is watched by exactly two enabled cameras (exact double-coverage over overlapping candidate groups).",
 "n": 4,
 "constraints": [
  {
   "type": "choose_exactly",
   "k": 2,
   "nodes": [
    0,
    1,
    2
   ]
  },
  {
   "type": "choose_exactly",
   "k": 2,
   "nodes": [
    1,
    2,
    3
   ]
  },
  {
   "type": "choose_exactly",
   "k": 2,
   "nodes": [
    0,
    3
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example security_dual_watch --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/security_dual_watch        # the full example over HTTP

⊕ GF(2) Consistency Check

Security · command xorsat · effort flash · id: security_gf2_consistency

Every parity clause is checked independently over GF(2).

Recover a binary assignment that satisfies a small parity system. This is a transfer recipe: change the entities, measurements, constraints and scale while preserving the command contract.

Reading the answer

XOR every returned clause over GF(2)

Where this shows up

Data integrity, IoT, Education

The same encoding also solves 3

  • XOR consistency diagnosisData integrity
    XOR checks → clauses
  • Binary sensor reconciliationIoT
    XOR relations → clauses
  • Constraint puzzleEducation
    exclusive-or clues → clauses

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Recover a binary assignment that satisfies a small parity system.",
 "n": 6,
 "clauses": [
  {
   "vars": [
    0,
    1,
    2
   ],
   "parity": 0
  },
  {
   "vars": [
    1,
    3
   ],
   "parity": 1
  },
  {
   "vars": [
    2,
    4,
    5
   ],
   "parity": 1
  },
  {
   "vars": [
    0,
    5
   ],
   "parity": 1
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "satisfied": 4,
 "total": 4,
 "all_satisfied": true,
 "certainty": "certified optimum (independently checked)"
}

Run it

terminal
hexstellar example security_gf2_consistency --format json | hexstellar solve xorsat
curl -s https://api.hexstellar.com/api/v1/examples/security_gf2_consistency        # the full example over HTTP

Space

🛰️ Satellite Conjunction De-confliction

Space · command rules · effort flash · id: space_maneuver_deconfliction

The exclusion binds two candidate choices, not the two actors; a fix creates new conflicts, so screen and exclude those pairs too.

Four spacecraft each have a maneuver menu: hold, raise orbit, lower orbit. If A and B both hold, they meet at closest approach. Fixing that is not enough: B raising its orbit would create a NEW conjunction with C fifteen minutes later, so the fix and C's hold can't both be chosen. D is below its fuel reserve and may not burn at all, and C's lower burn would break a protected science pointing window. HexStellar returns one maneuver per spacecraft such that no forbidden pair of choices coexists — a jointly safe traffic plan, not four locally safe ones. In this instance the plan needs only a single burn: A raises, everyone else holds. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

Nodes 0-2 are Sat A's candidates (hold/raise/lower), 3-5 Sat B, 6-8 Sat C, 9-11 Sat D. answer[i] is 1 when that candidate maneuver is the one chosen for its spacecraft. violations is 0 when every spacecraft has exactly one maneuver and no conjunction pair, fuel rule, or pointing rule is broken.

Where this shows up

Space traffic coordination for mega-constellations, autonomous conjunction screening, onboard maneuver negotiation between operators, launch and reentry corridor planning — anywhere many movers must agree on a joint plan faster than a human coordination loop.

The same encoding also solves 7

  • Assigning each departure a standard route so no two chosen routes lose separation at a shared merge fixAviation
    spacecraft → departing flights, maneuver menu → the standard departure routes each flight is cleared for, choose_one → one route per flight, mutual_exclusion → a specific route-of-flight-A with route-of-flight-B pair that converges inside the separation minimum, force_false → a route the aircraft is not equipped or certified to fly
  • Choosing a switching state per substation so no chosen combination overloads a line under an N-1 contingencyEnergy
    spacecraft → substations, maneuver menu → switching configurations (normal, tie open, tie closed), choose_one → one configuration per substation, mutual_exclusion → a configuration pair that leaves a line over its rating when the contingency is applied, including the overloads a reconfiguration itself creates elsewhere, force_false → a configuration blocked by a breaker under maintenance
  • Picking one version per service so no chosen pair of versions has an incompatible contractRelease Engineering
    spacecraft → services in the release train, maneuver menu → the candidate versions of each service, choose_one → exactly one version ships per service, mutual_exclusion → a version pair with an incompatible wire contract, force_false → a version yanked or not certified for the region; a hard dependency (A v2 needs B v3 or later) is a requires rule in the same command
  • Selecting an operating mode per unit so no chosen pair of modes trips a safety interlockProcess Manufacturing
    spacecraft → plant units, maneuver menu → operating modes (run, reduced rate, regeneration), choose_one → one mode per unit, mutual_exclusion → a mode pair that violates an interlock on a shared header or flare, force_false → a mode locked out while a catalyst cure is in progress
  • Choosing one precomputed route per mobile robot so no two chosen routes claim the same aisle segment in the same windowWarehouse Robotics
    spacecraft → mobile robots, maneuver menu → the precomputed routes offered to each robot, choose_one → one route per robot, mutual_exclusion → a route pair that occupies one aisle segment in the same window, including the reroute that pushes a robot into a third robot's aisle, force_false → a route crossing a closed or blocked aisle
  • Scheduling maintenance jobs into change windows so no chosen pair takes down both halves of a redundant pathIT Operations
    spacecraft → maintenance jobs, maneuver menu → the change windows each job may take, choose_one → one window per job, mutual_exclusion → a (job, window) candidate paired with another (job, window) candidate that would remove both halves of one redundant path at once, force_false → a window inside a business freeze for that job
  • Assigning each tower crane an operating sector so no two chosen sectors sweep the same airspaceConstruction
    spacecraft → tower cranes, maneuver menu → the sectors each crane may be slewed to, choose_one → one sector per crane, mutual_exclusion → a sector pair whose sweeps overlap in plan and in height, force_false → a sector barred by an overhead line or a neighbour's oversail restriction

Measured at scale actually run

The same menu encoding at 100,000 candidate maneuvers — 10,000 spacecraft choosing one of ten each — under 30,000 screened conjunction, fuel and pointing rules returns a joint plan whose rule-violation count is certified minimal and independently checked. That certificate covers the encoding, not the sky: this example's independent re-check of the screening set still applies before any burn is committed.

Instance
100,000 variables · 30,000 rules
Answer
certified
Engine time
985 ms (969 ms–985 ms, n=3)
Peak memory
16.2 MB
Request
1,602 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only rules --sizes target

How the encoding grows

The identical shape for 2,000 actors with 8 candidate options each is 16,000 booleans and 2,000 choose_one rules; every screened pair of actors contributes one mutual_exclusion per forbidden combination of their options, so 5,000 flagged pairs averaging 3 bad combinations is 15,000 exclusions, and one flagged pair can carry at most 8 x 8 = 64. Add one force_false per option ruled out in advance. That is the same structure as the 12-boolean instance here, in one request. Certification is reported per answer and is not decided by the size of the screening set: a 100,000-boolean rule set carrying 30,000 rules has come back certified, so read the label the answer carries rather than assuming a bigger screening set must be a labelled heuristic. Either way the label covers the encoding, and this example's notes require an independent re-check of the physical world before any plan is acted on.

The encoding recipe (agent notes)

ENCODING RECIPE: each spacecraft maneuver menu becomes one boolean per candidate plus choose_one over that menu. A screened conjunction is mutual_exclusion between the two candidate choices that produce it, never between the spacecraft as abstract entities. Fuel, pointing and corridor prohibitions are force_false. A real propagator or screener stays upstream, must examine the whole horizon including conflicts created by a proposed burn, and must re-propagate the selected plan afterward. This rules recipe is feasibility-only: it does not accept delta-v, fuel, risk or preference objective fields. Do not invent them and do not claim that a zero-violation plan is the cheapest plan. If cost matters, use a separately validated cost-bearing optimize/milp formulation or bounded simulator composition and independently re-check the identical hard exclusions; until a one-call cost-bearing rules contract is published, keep feasibility and cost as separate evidence. Start at flash, inspect broken_constraints and unassigned_nodes when present, open the option menu only for trapped actors, and remember that certainty covers the submitted encoding rather than flight safety.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Pick one maneuver per spacecraft so no chosen pair of choices still collides — including the conflicts a maneuver creates later.",
 "n": 12,
 "constraints": [
  {
   "type": "choose_one",
   "nodes": [
    0,
    1,
    2
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    3,
    4,
    5
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    6,
    7,
    8
   ]
  },
  {
   "type": "choose_one",
   "nodes": [
    9,
    10,
    11
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    0,
    3
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    4,
    6
   ]
  },
  {
   "type": "mutual_exclusion",
   "nodes": [
    2,
    9
   ]
  },
  {
   "type": "force_false",
   "nodes": [
    10
   ]
  },
  {
   "type": "force_false",
   "nodes": [
    11
   ]
  },
  {
   "type": "force_false",
   "nodes": [
    8
   ]
  }
 ]
}

Expected (engine-verified)

expected.json
{
 "violations": 0
}

Run it

terminal
hexstellar example space_maneuver_deconfliction --format json | hexstellar solve rules
curl -s https://api.hexstellar.com/api/v1/examples/space_maneuver_deconfliction        # the full example over HTTP

Sustainability

🌱 Conservation Reserve Selection

Sustainability · command select · effort flash · id: conservation_reserve

Overlap is a penalty on the pair, so a negative entry rewards adjacency instead — one matrix expresses both spread-out and clustered picks.

A land trust can protect only so many parcels. Choosing the highest-value parcels one by one buys overlapping coverage — several parcels protecting the same species or carbon stock. HexStellar picks the set that maximizes total conservation value minus overlap, for the widest coverage per dollar — here three parcels that skip the redundant pairs. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is the chosen parcel indices; value is total conservation value minus pairwise coverage overlap; count is how many were selected (the budget).

Where this shows up

Reserve/protected-area design (the Marxan problem), carbon-project land portfolios, biodiversity offset selection, easement prioritization.

The same encoding also solves 8

  • Choose 30 of 700 available sites for a new store network where two sites inside one drive-time isochrone draw the same customersRetail real estate
    candidates → available sites, k → stores the capital plan opens, affinity → forecast catchment revenue at that site, redundancy → trade-area overlap between a site pair, the sales one store takes from the other
  • Select 25 of 400 candidate park-and-ride lots where two lots on one corridor capture the same commutersPublic transit
    candidates → candidate park-and-ride parcels, k → lots the programme builds, affinity → commuters diverted from the corridor by that lot, redundancy → commuter catchment shared by a lot pair
  • Choose 40 of 900 planned drill collars for a season when collars inside one hole spacing test the same ore blockMining / exploration
    candidates → planned drill collars, k → holes the rig programme completes, affinity → resource-classification uncertainty resolved by that hole, redundancy → ore-block volume the other hole in the pair already tests
  • Pick 14 of 220 candidate radar sites for an air-surveillance network where sites with overlapping lobes watch the same volumeDefense / ISR
    candidates → candidate radar sites, k → radars the acquisition funds, affinity → airspace volume newly covered from that site, redundancy → coverage volume shared with the other site in the pair
  • Choose 12 of 180 city blocks for a street-tree planting round where adjacent blocks relieve the same heat-island cellMunicipal government
    candidates → candidate planting blocks, k → blocks the season's crew and nursery stock cover, affinity → heat and stormwater benefit scored for that block, redundancy → heat-island cell benefit shared by a block pair
  • Select 9 of 130 candidate fire-station relocations where two stations inside one response-time contour reach the same incidentsPublic safety
    candidates → candidate station parcels, k → stations the bond issue builds, affinity → incidents brought inside the response standard from that parcel, redundancy → incidents both parcels in the pair already reach
  • Pick 22 of 350 candidate edge PoP cities where two PoPs on one transit path serve the same usersCloud infrastructure
    candidates → candidate edge PoP cities, k → PoPs the build budget funds, affinity → user population brought inside the latency target by that PoP, redundancy → user population both PoPs in the pair already serve
  • Choose 14 of 200 candidate depot locations for cyclone pre-positioning where two depots inside one road-access window supply the same districtsHumanitarian logistics
    candidates → candidate depot locations, k → depots the pre-positioning budget stocks, affinity → at-risk population reachable from that depot inside the access window, redundancy → population both depots in the pair already reach

Measured at scale actually run

2,000 candidate parcels narrowed to 80 protected, with 20,000 non-zero overlapping-coverage pairs charged against the total, returned a full slate of exactly 80 parcels — labelled heuristic (hypothesis — verify), so re-score it with the free verify call rather than treating it as a certified reserve.

Instance
2,000 candidates · 80 k · 20,000 overlap pairs
Answer
heuristic (labelled)
Engine time
5 ms (4 ms–5 ms, n=3)
Peak memory
5.8 MB
Request
11,729 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only select --sizes target

How the encoding grows

The identical encoding at 4,000 candidate parcels with 120 protected is 4,000 affinity values and up to 7,998,000 distinct pair penalties (a 16,000,000-entry symmetric matrix) in a single request, with the same four fields: m, k, affinity, redundancy. Certification is proven by exhaustion and is labelled on the answer, so an instance this size returns a stated heuristic while the chosen count remains exactly 120.

The encoding recipe (agent notes)

THE MARXAN PROBLEM AS select: affinity is each parcel's conservation value (biodiversity + carbon coverage); redundancy is overlap — two parcels protecting the SAME feature earn less together. Maximizing Σ affinity − Σ redundancy is exactly the maximal-coverage objective, and every answer carries its certainty label — certified at small parcel counts, a stated hypothesis at reserve scale. COMMON MISTAKES: (1) omitting redundancy → you buy overlapping coverage and waste budget; the overlap matrix is the whole value of the method; (2) wanting CONNECTIVITY (adjacent parcels preferred for a contiguous reserve) — that's a NEGATIVE redundancy (a reward) between neighbors, or better modeled in optimize where you can reward adjacency directly; (3) sign confusion — affinity is value, redundancy is overlap penalty. THE REACH: identical to biomarker-panel and RAG-context selection — pick k, maximize coverage, avoid paying twice. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Select the parcels that cover the most biodiversity/carbon without paying for overlap.",
 "m": 8,
 "k": 3,
 "affinity": [
  8,
  9,
  7,
  6,
  9,
  4,
  7,
  5
 ],
 "redundancy": [
  [
   0,
   8,
   0,
   0,
   2,
   0,
   0,
   0
  ],
  [
   8,
   0,
   0,
   0,
   2,
   0,
   0,
   0
  ],
  [
   0,
   0,
   0,
   6,
   0,
   0,
   1,
   0
  ],
  [
   0,
   0,
   6,
   0,
   0,
   0,
   0,
   3
  ],
  [
   2,
   2,
   0,
   0,
   0,
   5,
   0,
   0
  ],
  [
   0,
   0,
   0,
   0,
   5,
   0,
   0,
   0
  ],
  [
   0,
   0,
   1,
   0,
   0,
   0,
   0,
   6
  ],
  [
   0,
   0,
   0,
   3,
   0,
   0,
   6,
   0
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "value": 23,
 "count": 3,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example conservation_reserve --format json | hexstellar solve select
curl -s https://api.hexstellar.com/api/v1/examples/conservation_reserve        # the full example over HTTP

♻️ Recycling Line Dispatch & Sizing

Sustainability · command milp · effort flash · id: recycling_line_dispatch

No slack variable for off-means-zero: linear +38 per tonne, binary×tonnage pair −50, so an idle line pays 38 a tonne and snaps to 0.

A materials-recovery plant has two sorting lines: line A (small, up to 4 t/h, changeover cost 5) and line B (larger, up to 6 t/h, changeover cost 10). Revenue is 12 per tonne, but two effects push back: each line's processing cost grows with the square of its throughput (congestion), and total output saturates the buyer's market, so the lines interact — routing more through A lowers the marginal value of B's tonnes. HexStellar decides both layers at once: spin up BOTH lines and run each at 3 t/h (objective −21). The tempting shortcut — run only the cheap line flat-out at its 4 t/h cap — scores −19, and the big line alone scores −14: splitting the load beats saturating either line, and only a joint binary+continuous solve sees that. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer is [run line A (0/1), run line B (0/1), tonnes/h through A, tonnes/h through B]. objective is the minimized net cost (negative = profit): changeover costs + quadratic congestion + market saturation − revenue. Here [1, 1, 3, 3] with objective −21.

Where this shows up

Materials-recovery and sorting plants, batch chemical processing, print/cutting shops, bakery ovens, cloud batch clusters — anywhere the decision is 'which machines do we turn on' AND 'how hard do we run each', and the machines share one market, budget, or downstream buffer.

The same encoding also solves 8

  • Unit commitment for a peaking generator fleet over one dispatch intervalEnergy
    lines → generating units, changeover cost → each unit's start-up cost on its binary, tonnes/h → MW dispatched on a continuous variable bounded [0, max], congestion diag → the unit's rising incremental heat rate, market-saturation cross term → the price depression the fleet's own combined output causes, revenue → value per MWh as the negative linear term, on/off link → a unit not started dispatches 0 MW. A minimum-stable-generation floor is not a box bound here: fix that unit on (declare it continuous with lo=hi=1) and re-solve with output bounded [min, max] to price that pattern.
  • Splitting a large parent order across execution venues under market impactFinance
    lines → venues, changeover cost → the fixed connectivity and clearing fee charged the moment a venue is used at all, tonnes/h → shares routed there on a continuous variable bounded by its displayed size, diag → that venue's own impact cost, which grows with the square of the size sent, cross term → the shared-book impact two venues inflict on each other, revenue → the per-share spread capture as the negative linear term, on/off link → an unused venue routes 0 shares. The parent size is a term this shape does not carry for free: milp takes no constraints, so add (sum of routed shares - Q)^2 expanded by hand into linear, diag and the venue-venue quadratic pairs - the same squared-equality technique the counterweight example uses - or the answer routes only what is profitable rather than the whole order.
  • Which pumps to start and their flow setpoints on a shared trunk mainUtilities (Water)
    lines → pumps, changeover cost → the start and wear cost on each pump's binary, tonnes/h → m^3/h through the pump bounded by its curve limit, diag → friction head loss, which rises with the square of flow, cross term → the extra head two pumps impose on each other through the shared main, revenue → the value of water delivered, on/off link → a stopped pump passes 0 flow
  • Which carriers to bring into service on a cell site and at what transmit powerTelecom
    lines → carriers, changeover cost → the fixed cost of putting a carrier into service, tonnes/h → transmit power on a continuous variable bounded by the licensed maximum, diag → amplifier efficiency loss rising with the square of power, cross term → measured inter-carrier interference between two carriers on the same site, revenue → traffic served per watt, on/off link → a dark carrier radiates 0
  • Channel budget allocation where two channels reach the same audienceMarketing
    lines → paid channels, changeover cost → the minimum contract fee that applies the moment a channel is used at all, tonnes/h → spend on a continuous variable bounded by that channel's available inventory, diag → diminishing response within the channel, cross term → audience overlap that makes the second impression on the same person worth less, revenue → response value per unit of spend, on/off link → an unused channel takes 0 spend. There is no total-budget cap in this encoding - spend is bounded per channel only, and a ceiling is an inequality milp cannot state: either target the budget exactly with a (sum of spend - B)^2 term expanded into linear/diag/quadratic, or check the returned total against the real budget before committing.
  • Autoscaling an inference pool across instance types sharing one rack power budgetCloud infrastructure
    lines → instance types, changeover cost → the reservation and warm-up cost of holding any capacity of that type, tonnes/h → requests per second routed to it on a continuous variable bounded by measured capacity, diag → queueing cost rising with the square of the load placed on it, cross term → the shared rack power and thermal budget the two types compete for, revenue → value per request served, on/off link → a type with no instances takes 0 traffic. Note the cross term PRICES the shared budget; a hard cap is an inequality and needs a slack variable, so verify the returned totals against the real limit
  • Which batch reactors to charge and at what batch rateChemicals
    lines → reactors, changeover cost → the clean-out cost incurred whenever a reactor is charged, tonnes/h → batch rate on a continuous variable bounded by the vessel's safe rate, diag → cooling duty rising with the square of the rate, cross term → the shared steam header both reactors draw from, revenue → product value per tonne, on/off link → an idle reactor runs at 0
  • Which pits to mobilise and how many tonnes to haul from each to one concentratorMining
    lines → pits, changeover cost → mobilising the fleet to that pit, tonnes/h → tonnes hauled on a continuous variable bounded by the haul road's capacity, diag → ramp queueing cost rising with the square of the haul rate, cross term → the concentrator feed both pits share, so extra tonnes from one lower the marginal value of the other's, revenue → recovered metal value per tonne, on/off link → an unmobilised pit ships 0

Measured at scale actually run

At 1,500 candidate sorting lines the same encoding carries 1,500 on/off binaries, 1,500 bounded tonnes-per-hour variables and 12,000 congestion and market-saturation couplings in a single 350 KB request, and returns a complete which-lines-and-how-much dispatch. That answer is labelled heuristic rather than certified, so hold the returned binaries fixed and re-derive the continuous optimum for that on/off pattern before committing the plan.

Instance
1,500 binary · 1,500 continuous · 12,000 pair terms
Answer
heuristic (labelled)
Engine time
37 ms (36 ms–37 ms, n=3)
Peak memory
3.1 MB
Request
350 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only milp --sizes target

How the encoding grows

The identical shape at 200 candidate units is 400 variables (one binary and one bounded continuous each), 400 linear coefficients, 200 diag curvature entries, 200 on/off link pairs and C(200,2) = 19,900 cross terms — 20,100 quadratic triples in one request, over 2^200 on/off patterns. Only the counts grow; the four term families do not. milp labels the answer heuristic, so with the returned binaries held fixed the remaining continuous part is convex and you re-derive its optimum yourself to confirm.

The encoding recipe (agent notes)

THIS IS THE MIXED yes/no + how-much PATTERN. THE ENCODING RECIPE: a binary per on/off decision (changeover cost on its linear term), a continuous variable with box bounds [0, capacity] per throughput. The on/off LINK needs no slack variable: add +M to the continuous variable's linear term and −M on the (binary × continuous) quadratic pair — when the line is on the two cancel down to the tonne's real net cost, and when it is off the surviving positive linear term makes any positive throughput expensive, so it snaps to 0. In this payload that link is folded together with the 12-per-tonne revenue: the linear term is M = 50 minus that revenue, i.e. 38, against a pair of −50 — so an on tonne carries a net linear −12 and an off tonne a net linear +38. Diminishing returns are the diag entries (note the objective uses ½·q·x², so diag 3 means 1.5·t²), and the MARKET-SATURATION coupling is the cross quadratic term between the two throughputs. COMMON MISTAKES: (1) forgetting the coupling — if the lines share nothing, each line optimizes ALONE and you don't need a solver at all; check for a shared market, budget, or buffer before reaching for this tool; (2) modeling 'can't run when off' as a rule — milp has no constraint list; preconditions become penalty terms like the M·t·(1−x) link here; (3) trusting certainty blindly — milp reports heuristic; with the binaries fixed this objective is convex, so verify by re-deriving the continuous optimum for the returned on/off pattern (and for its neighbors) — here brute-forcing all four on/off patterns confirms −21 as the true global optimum, the other three scoring 0, −19 and −14; (4) inequality targets ('deliver AT LEAST 80t') need slack variables or care with penalty shapes — prefer formulations, like this one, where every penalty vanishes exactly at the intended optimum. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Decide which sorting lines to spin up AND how many tonnes to route through each — a yes/no and a how-much in one solve.",
 "vars": [
  {
   "domain": "binary"
  },
  {
   "domain": "binary"
  },
  {
   "domain": "continuous",
   "lo": 0,
   "hi": 4
  },
  {
   "domain": "continuous",
   "lo": 0,
   "hi": 6
  }
 ],
 "linear": {
  "0": 5,
  "1": 10,
  "2": 38,
  "3": 38
 },
 "diag": {
  "2": 3,
  "3": 3
 },
 "quadratic": [
  [
   2,
   3,
   1
  ],
  [
   0,
   2,
   -50
  ],
  [
   1,
   3,
   -50
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "objective": -21.0,
 "certainty": "heuristic (hypothesis - verify; global optimum for a convex problem, otherwise a strong local optimum)"
}

Run it

terminal
hexstellar example recycling_line_dispatch --format json | hexstellar solve milp
curl -s https://api.hexstellar.com/api/v1/examples/recycling_line_dispatch        # the full example over HTTP

Telecom

📡 Interference-Aware Band Assignment

Telecom · command maxcut · effort flash · id: telecom_band_assignment

A cost paid only when a pair shares a bucket inverts: maximize the cut, minimize the cost — what you pay is total weight minus cut_value.

Six transmitters must each be assigned to one of two frequency bands. Every pair carries an interference weight that is only paid when both sit in the same band. HexStellar splits them into two bands so the interference that must be paid is as small as it can possibly be — and for this size it proves the residual is the minimum achievable. Here 6 units of interference are unavoidable (forced by the graph's odd-cycle structure, not by any single triangle), and HexStellar finds the assignment that leaves exactly that and no more. Use this as a formulation template: replace the entities and measurements, add domain constraints deliberately, and scale only after validating the smaller model.

Reading the answer

answer[i] is the band (0 or 1) of transmitter i. cut_value is the interference SEPARATED across bands; the interference still paid is (total edge weight − cut_value). Bigger cut = less co-band interference.

Where this shows up

Frequency and channel assignment, Wi-Fi/cell band planning, time-slot separation, two-coloring to minimize same-group cost.

The same encoding also solves 7

  • Splitting a departure bank between two runways so pairs that need wake-turbulence separation do not share a runwayAviation
    nodes → departing flights, edge weight → the separation penalty that pair costs when both use one runway, answer[i] → the runway flight i is given, penalty actually paid → total edge weight - cut_value. Equal loading of the two runways is not a field this command has: restate the same weights in rules as linear -w on each endpoint plus quadratic +2w on the pair, then add choose_exactly k over the runway-1 indicators
  • Distributing reagents between two storage cabinets so incompatible chemicals are never stored togetherLaboratory safety
    nodes → reagents, edge weight → the incompatibility severity of that pair (oxidizer with fuel, acid with base, water-reactive with aqueous), answer[i] → the cabinet reagent i is stored in, residual co-stored hazard → total edge weight - cut_value
  • Placing spots into the two ad pods of one commercial break so directly competing brands never run in the same podAdvertising
    nodes → booked spots, edge weight → the brand-conflict cost of that pair sharing a pod, answer[i] → the pod spot i airs in, conflict cost paid → total edge weight - cut_value
  • Allocating admitted patients to two ward bays so pairs carrying a cross-transmission risk are not housed togetherHealthcare
    nodes → admitted patients, edge weight → the modelled transmission risk of that pair when co-housed (colonization status, susceptibility, indwelling-device burden), answer[i] → the bay patient i is placed in, residual risk → total edge weight - cut_value
  • Splitting an exam cohort into two sittings so candidates with a collusion risk do not sit at the same timeEducation
    nodes → candidates, edge weight → the collusion risk of that pair (same prep group, prior adjacent seating, shared submission history), answer[i] → the sitting candidate i takes, risk paid → total edge weight - cut_value. Three or more sittings is a different encoding rather than a bigger one: use rules with one binary per (candidate, sitting), a choose_one per candidate, and quadratic +risk on every same-sitting pair
  • Placing a deal team on the two sides of an information barrier so conflicted individuals never share a sideLegal
    nodes → individuals staffed on the matter, edge weight → the conflict severity of that pair (opposing-client history, prior mandate, family tie), answer[i] → the side of the barrier individual i works behind, unresolved conflict → total edge weight - cut_value
  • Drawing a tournament field into two pools so entrants from the same club or nation avoid an early clashSports
    nodes → entrants, edge weight → the early-clash penalty of that pair sharing a pool (same club, same nation, same qualifying event), answer[i] → the pool entrant i is drawn into, clash penalty paid → total edge weight - cut_value

Measured at scale actually run

The same shape holding 8,000 transmitters and 80,000 interfering pairs is submitted as one 1,314 KB request and answered with one band bit per transmitter, labelled heuristic instead of the proven minimum the six-transmitter instance here gets — so the residual co-band interference it implies (total edge weight - cut_value) is a hypothesis to re-check with the free verify call, not yet a floor you can publish.

Instance
8,000 variables · 80,000 edges
Answer
heuristic (labelled)
Engine time
5.8 s (5.3 s–6.1 s, n=3)
Peak memory
69.6 MB
Request
1,314 KB

Apple M3 Pro · 12 cores · 36 GB · macOS 15.7.4 · Python 3.14.7 · single process · effort flash

An identical request is answered from the stored result rather than solved again, so re-running one of these echoes its original timing. Pass --seed to the script for a fresh instance; the range below is three different instances.

reproduce it
python3 hxs-cli/scale_instances.py --only maxcut --sizes target

How the encoding grows

The identical shape at 1,200 transmitters is one edge per interfering pair: 18,000 [i, j, cost] triples when each unit interferes with 30 others, 719,400 for the full pairwise matrix, and the answer is still one band bit per transmitter. The residual co-band cost stays a single subtraction, total edge weight - cut_value, over those same weights; the certainty label states per answer whether the split was exhausted and proven or returned as a labelled heuristic.

The encoding recipe (agent notes)

THE 'MINIMIZE SAME-GROUP COST = MAXIMIZE CUT' TRICK: whenever a cost is only paid when two items land in the SAME bucket, and there are two buckets, maximizing the cut minimizes that cost — because every edge you push across the boundary is a cost you avoid. Model each conflicting pair as an edge [i, j, cost]. The minimum unavoidable cost is (sum of all edge weights − cut_value). COMMON MISTAKES: (1) trying to force a zero-interference answer when the graph has an odd cycle of positive weights — some interference is mathematically unavoidable, and the certified cut_value tells you exactly how much; (2) reading cut_value as the interference paid — it's the interference AVOIDED; subtract it from the total to get what's paid; (3) more than two bands — this maps to two-way separation; three or more buckets is a different (graph-coloring) problem. CREATIVE USE: Do not just run these examples statically. Be creative. If you interpret the problem well, you can map almost anything into this solver. Mutate the constraints, expand the scale, and unleash your creativity.

The problem (runnable JSON)

problem.json
{
 "tag": "hexstellar-cortex-v1",
 "description": "Assign transmitters to two bands so co-band interference is provably minimal.",
 "n": 6,
 "edges": [
  [
   0,
   1,
   9
  ],
  [
   1,
   2,
   4
  ],
  [
   0,
   2,
   6
  ],
  [
   2,
   3,
   7
  ],
  [
   3,
   4,
   6
  ],
  [
   4,
   5,
   8
  ],
  [
   5,
   0,
   5
  ],
  [
   1,
   4,
   7
  ],
  [
   2,
   5,
   2
  ]
 ]
}

Expected (engine-verified)

expected.json
{
 "cut_value": 48,
 "certainty": "certified optimum (proven by exhaustion)"
}

Run it

terminal
hexstellar example telecom_band_assignment --format json | hexstellar solve maxcut
curl -s https://api.hexstellar.com/api/v1/examples/telecom_band_assignment        # the full example over HTTP

Using an example as a template

Every problem object already carries the required tag and a plain-sentence description — the provenance fields the API expects. Swap the numbers for your own, keep the shape, and preflight for free with --dry-run before spending a solve. The expected block is what the engine returned when the example was built; a certainty that starts with certified is a proven optimum, while heuristic answers are hypotheses you can re-check for free with hexstellar verify.