@ohtaman/washi 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.ja.md +22 -24
  2. package/README.md +20 -22
  3. package/README.zh-CN.md +25 -27
  4. package/dist/browser/{__vite-browser-external-rTVKos2U.js → solvers/highs-__vite-browser-external-Dn-83hnF.js} +1 -1
  5. package/dist/browser/{browser-runtime-AG5QFtKf.js → solvers/highs-browser-runtime-0Bgq5ksG.js} +1 -1
  6. package/dist/browser/{loader-i3FnqMes.js → solvers/highs-loader-BLY3wzDH.js} +25 -18
  7. package/dist/browser/{highs-worker.js → solvers/highs-worker.js} +1 -1
  8. package/dist/browser/solvers/highs.js +1414 -0
  9. package/dist/browser/washi.js +1090 -1473
  10. package/dist/browser/washi.min.js +4 -4
  11. package/dist/lib/solvers/glpk.js +34 -32
  12. package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
  13. package/dist/lib/solvers/highs.js +410 -0
  14. package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
  15. package/dist/lib/solvers/pumpkin-node-runtime.js +1 -1
  16. package/dist/lib/solvers/pumpkin-worker.js +1 -1
  17. package/dist/lib/solvers/pumpkin.js +247 -1146
  18. package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
  19. package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
  20. package/dist/lib/solvers/z3.js +125 -123
  21. package/dist/lib/washi.js +2426 -1340
  22. package/dist/types/index.d.ts +1 -2
  23. package/dist/types/index.d.ts.map +1 -1
  24. package/dist/types/modeler/index.d.ts +0 -1
  25. package/dist/types/modeler/index.d.ts.map +1 -1
  26. package/dist/types/modeler/model.d.ts +6 -7
  27. package/dist/types/modeler/model.d.ts.map +1 -1
  28. package/dist/types/modeler/solvers/index.d.ts +2 -1
  29. package/dist/types/modeler/solvers/index.d.ts.map +1 -1
  30. package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
  31. package/docs/examples/diet-sensitivity.md +33 -14
  32. package/docs/examples/ecommerce-coupons.md +17 -9
  33. package/docs/examples/index.md +34 -30
  34. package/docs/examples/knapsack.md +11 -5
  35. package/docs/examples/portfolio-qp.md +21 -8
  36. package/docs/examples/production.md +10 -5
  37. package/docs/examples/project-scheduling.md +25 -12
  38. package/docs/examples/shift-scheduling.md +27 -19
  39. package/docs/examples/smt-security.md +27 -12
  40. package/docs/examples/transportation.md +23 -13
  41. package/docs/examples/traveling-salesperson.md +34 -22
  42. package/docs/examples/unsat-core.md +27 -15
  43. package/docs/examples/vehicle-routing.md +74 -28
  44. package/docs/getting-started/ai-agents.md +129 -90
  45. package/docs/getting-started/coding-agents.md +60 -41
  46. package/docs/getting-started/cross-origin.md +27 -14
  47. package/docs/getting-started/index.md +23 -16
  48. package/docs/getting-started/runtimes.md +70 -40
  49. package/docs/guide/constraint-programming.md +74 -44
  50. package/docs/guide/constraints.md +71 -39
  51. package/docs/guide/decomposition.md +72 -42
  52. package/docs/guide/expressions.md +79 -48
  53. package/docs/guide/formulation-tips.md +46 -27
  54. package/docs/guide/objectives.md +55 -31
  55. package/docs/guide/unsat-core.md +56 -53
  56. package/docs/guide/variables.md +61 -28
  57. package/docs/solvers/custom-solver.md +155 -119
  58. package/docs/solvers/glpk.md +58 -17
  59. package/docs/solvers/highs.md +115 -43
  60. package/docs/solvers/index.md +33 -26
  61. package/docs/solvers/pumpkin.md +71 -63
  62. package/docs/solvers/z3.md +63 -25
  63. package/llms-full.txt +1623 -953
  64. package/llms.txt +125 -93
  65. package/package.json +29 -20
  66. package/skills/washi/SKILL.md +43 -22
  67. package/dist/browser/solvers/pumpkin.min.js +0 -1
  68. package/dist/lib/registry-dx7x4e5c.js +0 -1694
  69. /package/dist/browser/{highs.wasm → solvers/highs.wasm} +0 -0
  70. /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  71. /package/dist/lib/{__vite-browser-external-oLchLuMx.js → solvers/__vite-browser-external-oLchLuMx.js} +0 -0
  72. /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
  73. /package/dist/lib/{highs-browser-runtime.js → solvers/highs-browser-runtime.js} +0 -0
  74. /package/dist/lib/{highs-runtime.js → solvers/highs-runtime.js} +0 -0
  75. /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
  76. /package/dist/lib/{highs-worker.js → solvers/highs-worker.js} +0 -0
  77. /package/dist/lib/{highs.wasm → solvers/highs.wasm} +0 -0
  78. /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  79. /package/dist/lib/{loader-CDpPXN_F.js → solvers/loader-CDpPXN_F.js} +0 -0
  80. /package/dist/lib/solvers/{pumpkin-loader-Ow74Fa1B.js → loader-Ow74Fa1B.js} +0 -0
  81. /package/dist/lib/{rolldown-runtime-DtPi1Y-2.js → solvers/rolldown-runtime-DtPi1Y-2.js} +0 -0
@@ -4,20 +4,20 @@
4
4
  | :--- | :--- | :--- | :--- |
5
5
  | Combinatorial OR / Dantzig-Wolfe | HiGHS (default) | `m.solveColumnGeneration()`, `pricing`, `m.binary()`, `m.constraint()`, `expr` (`sum`) | <ul><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/13-vehicle-routing-column-generation.ts">Source Code</a></li><li><a href="/guide/decomposition">Decomposition Guide</a></li></ul> |
6
6
 
7
- The **Capacitated Vehicle Routing Problem (CVRP)** determines the minimum number of delivery vehicles needed to visit a set of customers, subject to vehicle cargo capacity, maximum customer stops per shift, and route duration limits.
7
+ This **Capacitated Vehicle Routing Problem (CVRP)** variant minimizes the number of delivery vehicles needed to serve every customer. In addition to vehicle cargo capacity, each route must respect maximum stops per shift and route duration limits.
8
8
 
9
- In a monolithic MIP formulation, enumerating all possible customer combinations and visit sequences leads to $O(2^n)$ binary variables. With **Column Generation (Dantzig-Wolfe Decomposition)**, routes are generated on demand:
10
- 1. **Restricted Master Problem (RMP)**: Solves a set partitioning problem that selects a subset of candidate routes so that every customer is visited once.
11
- 2. **Pricing Subproblem**: Uses the dual values (shadow prices) from the master LP relaxation to construct improving routes with negative reduced cost ($\bar{c} = 1 - \sum \pi_i < 0$) via cheapest insertion and 2-opt local search.
9
+ Enumerating all feasible routes upfront in a monolithic MIP causes the number of binary variables to explode as the number of customers $n$ grows—unordered subsets alone scale as $O(2^n)$, and ordered routes grow even faster. **Column Generation (Dantzig-Wolfe Decomposition)** avoids this by generating routes on demand:
10
+ 1. **Restricted Master Problem (RMP)**: Solves the set-partitioning **LP relaxation** over generated routes so every customer is visited exactly once, then solves the final MIP.
11
+ 2. **Pricing Subproblem**: Reads each customer's dual value (shadow price) $\pi_i$ from the master LP relaxation and uses cheapest insertion with 2-opt search to build a route $r$ with negative reduced cost $\bar{c}_r = 1 - \sum_{i \in r} \pi_i < 0$.
12
12
 
13
13
  ## Problem Inputs
14
14
 
15
- We consider a distribution network with a central depot at $(0, 0)$ and **50 customer locations**:
15
+ We consider a distribution network with a central depot at $(0, 0)$ and **50 customer locations** (demands of **1 to 4 units** each):
16
16
 
17
17
  - **Vehicle Cargo Capacity**: At most **10 units** per vehicle.
18
18
  - **Maximum Stops**: At most **4 customers** per route.
19
19
  - **Maximum Shift Duration**: At most **200 minutes** (transit time + service time) per route.
20
- - **Transit & Service Times**: Euclidean distances between nodes (1 unit = 1 minute) plus **10 minutes** of unloading service time per customer.
20
+ - **Transit & Service Times**: Integer-rounded Euclidean distances (`Math.round`) between nodes (1 unit = 1 minute) plus **10 minutes** of unloading time per customer.
21
21
 
22
22
  ## Implementation in WaSHI
23
23
 
@@ -26,10 +26,30 @@ We consider a distribution network with a central depot at $(0, 0)$ and **50 cus
26
26
  ```typescript
27
27
  import { Model, expr, minimize } from "@ohtaman/washi";
28
28
 
29
+ interface RouteMeta {
30
+ tour: string[];
31
+ travelTime: number;
32
+ totalTime: number;
33
+ }
34
+
35
+ interface CandidateCustomer {
36
+ id: string;
37
+ demand: number;
38
+ dual: number;
39
+ }
40
+
41
+ interface RouteConstraints {
42
+ dist: (a: string, b: string) => number;
43
+ serviceTimes: Record<string, number>;
44
+ vehicleCapacity: number;
45
+ maxStops: number;
46
+ maxRouteTime: number;
47
+ }
48
+
29
49
  // --- Extracted Routing Helpers ---
30
50
 
31
51
  // 2-opt local search to eliminate crossing paths in a tour
32
- function optimize2Opt(tour, dist) {
52
+ function optimize2Opt(tour: string[], dist: (a: string, b: string) => number): string[] {
33
53
  let best = [...tour];
34
54
  let improved = true;
35
55
 
@@ -49,8 +69,8 @@ function optimize2Opt(tour, dist) {
49
69
  return best;
50
70
  }
51
71
 
52
- // Inserts a customer into the tour at the position that minimizes detour distance
53
- function insertCheapest(tour, id, dist) {
72
+ // Inserts a customer into the tour at the position that minimizes added distance
73
+ function insertCheapest(tour: string[], id: string, dist: (a: string, b: string) => number): string[] {
54
74
  let bestPos = 1;
55
75
  let minCost = Infinity;
56
76
 
@@ -65,7 +85,11 @@ function insertCheapest(tour, id, dist) {
65
85
  }
66
86
 
67
87
  // Calculates transit time and total duration (transit + service) for a tour
68
- function calcRouteTime(tour, dist, serviceTimes) {
88
+ function calcRouteTime(
89
+ tour: string[],
90
+ dist: (a: string, b: string) => number,
91
+ serviceTimes: Record<string, number>
92
+ ) {
69
93
  let travelTime = 0;
70
94
  for (let i = 0; i < tour.length - 1; i++) {
71
95
  travelTime += dist(tour[i], tour[i + 1]);
@@ -75,8 +99,8 @@ function calcRouteTime(tour, dist, serviceTimes) {
75
99
  }
76
100
 
77
101
  // Pricing subproblem: Finds an improving route with negative reduced cost (1 - dualSum < 0)
78
- function findImprovingRoute(candidates, config) {
79
- let bestRoute = null;
102
+ function findImprovingRoute(candidates: CandidateCustomer[], config: RouteConstraints): string[] | null {
103
+ let bestRoute: string[] | null = null;
80
104
  let minReducedCost = -1e-4;
81
105
 
82
106
  for (const seed of candidates.slice(0, 15)) {
@@ -130,11 +154,11 @@ async function runCVRP() {
130
154
  });
131
155
 
132
156
  const nodes = Object.fromEntries([depot, ...customers].map((n) => [n.id, n]));
133
- const dist = (a, b) =>
157
+ const dist = (a: string, b: string) =>
134
158
  Math.round(Math.hypot(nodes[a].x - nodes[b].x, nodes[a].y - nodes[b].y));
135
159
  const serviceTimes = Object.fromEntries(customers.map((c) => [c.id, c.serviceTime]));
136
160
 
137
- const routeConfig = { dist, serviceTimes, vehicleCapacity, maxStops, maxRouteTime };
161
+ const routeConfig: RouteConstraints = { dist, serviceTimes, vehicleCapacity, maxStops, maxRouteTime };
138
162
 
139
163
  // 1. Build Restricted Master Problem (RMP)
140
164
  const master = new Model("CVRP_FleetMaster");
@@ -143,7 +167,7 @@ async function runCVRP() {
143
167
  const initialRoutes = customers.map((c) => master.binary(`route_init_${c.id}`));
144
168
  master.objective(minimize(expr`sum(${initialRoutes})`));
145
169
 
146
- // Each customer must be visited by exactly 1 vehicle
170
+ // Set-partitioning constraints: each customer must be visited by exactly 1 vehicle
147
171
  const visitConstrs = customers.map((c, i) =>
148
172
  master.constraint(expr`${initialRoutes[i]} == 1`, `visit_${c.id}`)
149
173
  );
@@ -152,7 +176,7 @@ async function runCVRP() {
152
176
  console.log("Solving via Column Generation with dual-directed heuristic pricing...");
153
177
 
154
178
  // 2. Solve via Column Generation
155
- const result = await master.solveColumnGeneration({
179
+ const result = await master.solveColumnGeneration<RouteMeta>({
156
180
  finalizeAsMIP: true,
157
181
  pricing: async () => {
158
182
  // 1. Sort customers by shadow price (dual profit) descending
@@ -167,14 +191,14 @@ async function runCVRP() {
167
191
 
168
192
  // 3. Propose new column to Restricted Master Problem
169
193
  const { travelTime, totalTime } = calcRouteTime(bestRoute, dist, serviceTimes);
170
- const coefficients = {};
194
+ const coefficients: Record<string, number> = {};
171
195
  for (const id of bestRoute.slice(1, -1)) {
172
196
  coefficients[`visit_${id}`] = 1;
173
197
  }
174
198
 
175
199
  return {
176
200
  cost: 1,
177
- type: "Binary",
201
+ type: "Binary" as const,
178
202
  coefficients,
179
203
  meta: { tour: bestRoute, travelTime, totalTime },
180
204
  };
@@ -186,10 +210,21 @@ async function runCVRP() {
186
210
  console.log(`Total Columns Generated: ${result.columnsAdded}`);
187
211
 
188
212
  console.log("\nSample routes selected in fleet:");
189
- const activeRoutes = result.generatedColumns.filter((c) => c.variable.value === 1);
213
+ const activeRoutes: RouteMeta[] = [];
214
+ for (const c of result.generatedColumns) {
215
+ if (c.variable.value === 1 && c.proposal.meta) {
216
+ activeRoutes.push(c.proposal.meta);
217
+ }
218
+ }
219
+ for (let i = 0; i < customers.length; i++) {
220
+ if (initialRoutes[i].value === 1) {
221
+ const tour = ["Depot", customers[i].id, "Depot"];
222
+ const { travelTime, totalTime } = calcRouteTime(tour, dist, serviceTimes);
223
+ activeRoutes.push({ tour, travelTime, totalTime });
224
+ }
225
+ }
190
226
  for (const r of activeRoutes.slice(0, 5)) {
191
- const meta = r.proposal.meta;
192
- console.log(` ${meta?.tour.join(" -> ")} (Transit: ${meta?.travelTime}m, Total: ${meta?.totalTime}m)`);
227
+ console.log(` ${r.tour.join(" -> ")} (Transit: ${r.travelTime}m, Total: ${r.totalTime}m)`);
193
228
  }
194
229
  }
195
230
 
@@ -198,11 +233,22 @@ runCVRP();
198
233
 
199
234
  </CodeRunner>
200
235
 
201
- ## Notes
236
+ ## Key Takeaways
237
+
238
+ Starting from `50` single-customer vehicles, heuristic pricing generates `63` additional route columns and lowers the LP relaxation to about `12.65`. Finalizing that column pool as a MIP (root-node Price-and-Branch) yields a `19`-vehicle fleet made up of `11` multi-stop routes and `8` single-customer routes.
239
+
240
+ ### Master Problem, Pricing & Route Metadata
241
+
242
+ The master problem handles the LP relaxation and final set-partitioning MIP. Inside `pricing`, `visitConstrs[i].dual` supplies each customer's dual value (shadow price) to guide route construction. Storing `{ tour, travelTime, totalTime }` in `meta` lets you inspect the chosen stop sequence via `result.generatedColumns` after solving.
243
+
244
+ ### Set Partitioning (`== 1`) vs. Set Covering (`>= 1`)
245
+
246
+ This example uses `== 1` so no customer is visited twice in the final MIP. In larger instances, using `>= 1` keeps dual values non-negative ($\pi_i \ge 0$) and stabilizes LP convergence. When travel distances satisfy the triangle inequality, duplicate visits can be stripped after solving without increasing travel time, load, stop count, or fleet size. Note that rounding distances with `Math.round`, as in this example, can introduce small rounding violations of the triangle inequality.
247
+
248
+ ### Heuristic Pricing vs. Exact ESPPRC
249
+
250
+ Here `findImprovingRoute` runs a greedy cheapest-insertion and 2-opt heuristic instead of an exact Elementary Shortest Path Problem with Resource Constraints (ESPPRC) solver. Returning `null` therefore means the heuristic found no further improving route, rather than proving global LP optimality.
251
+
252
+ ### Price-and-Branch (`finalizeAsMIP: true`)
202
253
 
203
- - **Master Problem and Pricing Separation**: The master problem solves the LP relaxation and final set-partitioning MIP, while the `pricing` callback searches for negative-reduced-cost routes using cheapest insertion and 2-opt local search.
204
- - **Dual Value Access**: Dual values from the master LP relaxation are read from `visitConstrs[i].dual` to prioritize customers with higher shadow prices during route construction.
205
- - **Route Metadata**: Each proposed column attaches `{ tour, travelTime, totalTime }` under `meta`, allowing the ordered stop sequence to be inspected from `result.generatedColumns` after the solve completes.
206
- - **Set Partitioning (`== 1`) vs. Set Covering (`>= 1`)**: This example uses `== 1` so that the final MIP never covers a customer twice. In large-scale column generation, formulating coverage as `>= 1` restricts the dual prices to $\pi_i \ge 0$, avoiding negative dual oscillations; if the final MIP selects overlapping routes, duplicate visits can be removed by post-processing whenever distances satisfy the triangle inequality.
207
- - **Heuristic Pricing vs. Exact ESPPRC**: Because `findImprovingRoute` uses a fast greedy heuristic (cheapest insertion + 2-opt) instead of an exact Elementary Shortest Path Problem with Resource Constraints (ESPPRC) solver, returning `null` means no further improving columns were found by the heuristic rather than proving global LP optimality.
208
- - **Price-and-Branch (`finalizeAsMIP: true`)**: Solving the Restricted Master Problem as a MIP over the columns generated at the root node is known as the *Restricted Master Heuristic* (Price-and-Branch). It produces near-optimal integer fleets quickly without requiring full Branch-and-Price tree search.
254
+ Solving the Restricted Master Problem as a MIP over the columns generated at the root node is called the **Restricted Master Heuristic** (Price-and-Branch). It produces strong integer fleets quickly without implementing a full Branch-and-Price search tree.
@@ -1,22 +1,23 @@
1
1
  # AI Coding Agent Quick-Reference Guide
2
2
 
3
- > **Scope Note**: This document is the **consumer modeling quick-reference** for AI coding agents and developers building optimization or satisfiability models with `@ohtaman/washi`.
4
- > - **Portable Agent Skill (`SKILL.md`)**: For an actionable end-to-end modeling, `toLpString()` inspection, `verify()` verification, and Pumpkin / Z3 `unsatCore` conflict-diagnosis workflow skill (compatible with Claude Code, Antigravity, Cursor, Codex, and other `SKILL.md`-aware agents), use [`skills/washi/SKILL.md`](https://github.com/ohtaman/washi/blob/main/skills/washi/SKILL.md) (also shipped in the npm package at `node_modules/@ohtaman/washi/skills/washi/SKILL.md`):
3
+ > **Scope Note**: This document is the **modeling quick reference** for AI coding agents and developers building optimization or satisfiability models with `@ohtaman/washi`.
4
+ >
5
+ > - **Portable Agent Skill**: Install the WaSHI Agent Skill ([`skills/washi/SKILL.md`](https://github.com/ohtaman/washi/blob/main/skills/washi/SKILL.md), also shipped at `node_modules/@ohtaman/washi/skills/washi/SKILL.md`) for an end-to-end modeling, verification, and conflict-diagnosis workflow:
5
6
  > ```bash
6
7
  > # Install directly via the skills CLI (skills.sh / vercel-labs/skills)
7
8
  > npx skills add ohtaman/washi
8
9
  >
9
- > # Or link/copy the packaged skill into your project's agent skills directory
10
+ > # Or copy the packaged skill into your project's agent skills directory
10
11
  > mkdir -p .agents/skills/washi
11
12
  > cp node_modules/@ohtaman/washi/skills/washi/SKILL.md .agents/skills/washi/SKILL.md
12
13
  > ```
13
- > - **Repository Review Guidelines**: For repository contribution and pull-request review rules, see [`AGENTS.md`](https://github.com/ohtaman/washi/blob/main/AGENTS.md) in the repository root.
14
+ > - **Repository Development & Code Review Guidelines**: See [`AGENTS.md`](https://github.com/ohtaman/washi/blob/main/AGENTS.md) in the repository root.
14
15
 
15
16
  ---
16
17
 
17
18
  ## 1. Package Imports & Deployment
18
19
 
19
- ### Node.js / Bundlers (Vite, Webpack, Next.js, Bun)
20
+ ### Node.js, Bun, & Bundlers (Vite, Webpack, Next.js)
20
21
 
21
22
  ```ts
22
23
  import {
@@ -39,11 +40,13 @@ import {
39
40
  not,
40
41
  implies,
41
42
  xor,
42
- setHighsWasmUrl,
43
43
  } from "@ohtaman/washi";
44
44
 
45
- // Bundled CP/LCG solver plugin (zero external dependencies; registers "pumpkin"):
46
- import { setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
45
+ // Bundled solvers: HiGHS (default) and Pumpkin (`{ solver: "pumpkin" }`) work out of the box with zero extra imports.
46
+ // Import solver subpaths only when configuring engine-specific classes or custom WASM URLs:
47
+ // import { HighsSolver, setHighsWasmUrl } from "@ohtaman/washi/solvers/highs";
48
+ // import { PumpkinSolver, setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
49
+
47
50
  // Optional solver plugins (require installing peer dependencies first):
48
51
  // npm install z3-solver
49
52
  import "@ohtaman/washi/solvers/z3";
@@ -53,34 +56,47 @@ import "@ohtaman/washi/solvers/glpk";
53
56
 
54
57
  ### Browser ESM & Classic Script Tags
55
58
 
56
- - **Browser ESM**:
57
- - Core (HiGHS built-in): `import { Model, expr, maximize } from "./washi/washi.js";`
58
- - Pumpkin plugin: `import "./washi/solvers/pumpkin.js";`
59
- - GLPK plugin: `import "./washi/solvers/glpk.js";`
60
- - Z3 plugin: `import "./washi/solvers/z3.js";`
61
- - **Classic `<script>` / CodePen (IIFE)**:
62
- - Core: `<script src="./washi/washi.min.js"></script>` (exposes global `Washi`)
63
- - Pumpkin plugin: `<script src="./washi/solvers/pumpkin.min.js"></script>` (registers `"pumpkin"`, exposes `WashiPumpkin`)
64
- - GLPK plugin: `<script src="./washi/solvers/glpk.min.js"></script>` (registers `"glpk"`, exposes `WashiGLPK`)
65
- - Z3 plugin: `<script src="./washi/solvers/z3.min.js"></script>` (registers `"z3"`, exposes `WashiZ3`)
59
+ Classic `<script>` tags load immediately invoked function expression (`IIFE`) bundles that attach a global namespace to `window` (optional solver plugins auto-register when `window.Washi` is present). Assuming `dist/browser/` is hosted at `./washi/`:
60
+
61
+ | Solver | Browser ESM (`<script type="module">`) | Classic `<script>` IIFE |
62
+ | --- | --- | --- |
63
+ | **Core (HiGHS & Pumpkin)** | `import { Model, expr, maximize } from "./washi/washi.js";` | `<script src="./washi/washi.min.js"></script>` (global `Washi`) |
64
+ | **HiGHS** *(subpath API)* | `import { HighsSolver, setHighsWasmUrl } from "./washi/solvers/highs.js";` | Bundled in `washi.min.js` (pass `{ wasmUrl }` per call) |
65
+ | **Pumpkin** *(subpath API)* | `import { PumpkinSolver, setPumpkinWasmUrl } from "./washi/solvers/pumpkin.js";` | Bundled in `washi.min.js` (pass `{ wasmUrl }` per call) |
66
+ | **GLPK** *(optional)* | `import "./washi/solvers/glpk.js";` | `<script src="./washi/solvers/glpk.min.js"></script>` (`WashiGLPK`) |
67
+ | **Z3** *(optional)* | `import "./washi/solvers/z3.js";` | `<script src="./washi/solvers/z3.min.js"></script>` (`WashiZ3`) |
66
68
 
67
69
  ### WebAssembly Asset & Runtime Rules
68
70
 
69
- 1. **Bundled WASM by default (no implicit CDN fallback)**:
70
- - In Node.js and modern bundlers, WebAssembly assets resolve relative to the module automatically.
71
- - In browser deployments, deploy the full `dist/browser/` directory (JS, Worker, and `.wasm` files) together. If a local WASM URL is missing or returns an HTML SPA fallback, initialization fails immediately and reports the attempted URL—it **never** silently switches to a public CDN.
72
- - In browser runtimes, to load `highs.wasm` or `pumpkin.wasm` from a custom location, call `setHighsWasmUrl("https://.../highs.wasm")` (or `await m.solve({ wasmUrl: "https://.../highs.wasm" })`) for HiGHS, or `setPumpkinWasmUrl("https://.../pumpkin.wasm")` (or `await m.solve({ solver: "pumpkin", wasmUrl: "https://.../pumpkin.wasm" })`) for Pumpkin (ignored in Node.js for HiGHS; for Pumpkin in Node.js, bundled local `pumpkin.wasm` is used by default unless overridden with a `file://` URL).
73
- - **Pumpkin runs without `COOP`/`COEP`**: Unlike Z3, Pumpkin (`@ohtaman/washi/solvers/pumpkin`) uses single-threaded WASM inside a regular Web Worker and does **not** require `SharedArrayBuffer` or Cross-Origin Isolation headers (`COOP`/`COEP`). It requires bounded finite integer/binary variables (`lb`, `ub` in `[-(2^30 - 1), 2^30 - 1]`) and integer linear coefficients/RHS, and supports `initialValue` warm starts across `solve()` and `check()` (no `Continuous`, `QuadExpr`, or `relax: true`).
74
- 2. **Z3 requires a Secure Context, Cross-Origin Isolation, and CORS in browsers**:
75
- - Z3 WebAssembly uses `SharedArrayBuffer` multithreading. Browser pages running Z3 must run in a secure context (`window.isSecureContext === true`, i.e., HTTPS or `localhost`) and be cross-origin isolated (`window.crossOriginIsolated === true`) by serving:
76
- - `Cross-Origin-Opener-Policy: same-origin` (on the document)
77
- - `Cross-Origin-Embedder-Policy: require-corp` (on the document)
78
- - `Cross-Origin-Resource-Policy: cross-origin` and `Access-Control-Allow-Origin` (on cross-origin script/WASM asset responses)
79
- - Importing `@ohtaman/washi` never auto-injects a Service Worker. When a secure context or cross-origin isolation is absent in a browser, Z3 rejects immediately with a descriptive error.
80
- 3. **Web Workers & Cancellation (`AbortSignal`)**:
81
- - Pre-solve cancellation (`signal.aborted` before execution starts) is supported across all solvers.
82
- - In browsers where `Worker` is available on a non-opaque effective origin (`window.origin !== "null"`), both **HiGHS** and **Pumpkin** run in dedicated Web Workers by default (`useWorker: true`). On opaque effective origins (`window.origin === "null"`, such as `file:` URLs or `sandbox="allow-scripts"` `<iframe>` embeds without `allow-same-origin`), both default to main-thread execution (`useWorker: false`). Passing `{ signal }` to `m.solve({ signal })` or `m.check({ signal })` preemptively terminates an in-flight Worker run (or cancels queued Worker requests).
83
- - On main-thread HiGHS (`useWorker: false` or in Node.js), cooperative mid-solve cancellation is supported when `abort()` is triggered synchronously inside an `onProgress` callback at a solver interrupt checkpoint; arbitrary asynchronous aborts from outside cannot preempt a blocked synchronous WASM thread until a callback checkpoint or completion. Main-thread / Node.js Pumpkin checks `should_abort` checkpoints across branching and termination hooks. Single-threaded WASM solvers without interrupt hooks (GLPK, Z3) check `signal` before execution starts.
71
+ #### Bundled WASM & Custom Asset URLs
72
+
73
+ - **Automatic resolution**: In Node.js and bundler builds, WaSHI resolves `.wasm` assets under `solvers/` relative to the module with no CDN fallback.
74
+ - **Browser self-hosting**: Deploy `dist/browser/` intact (entry scripts, `solvers/` runtime/worker/WASM assets, and chunks). Requests that hit missing URLs or HTML SPA fallbacks fail immediately and report the attempted URL.
75
+ - **Custom browser URLs**: Call `setHighsWasmUrl(url)` (from `@ohtaman/washi/solvers/highs`) or `setPumpkinWasmUrl(url)` (from `@ohtaman/washi/solvers/pumpkin`), or pass `{ wasmUrl }` to `m.solve()` / `m.check()`. This override is ignored for HiGHS in Node.js, while Pumpkin accepts `file://` URLs in Node.js. For Z3, call `setZ3Assets({ jsUrl, wasmUrl })` (from `@ohtaman/washi/solvers/z3`) or pass `{ z3JsUrl, z3WasmUrl }`.
76
+
77
+ #### Browser Security & Cross-Origin Isolation
78
+
79
+ - **HiGHS, Pumpkin, and GLPK**: Run in standard browser contexts without `SharedArrayBuffer` or isolation headers.
80
+ - **Z3 browser preconditions**: Z3 uses `SharedArrayBuffer` multithreading, so browsers require a Secure Context (`window.isSecureContext === true`, HTTPS or `localhost`) and `window.crossOriginIsolated === true`.
81
+ - **Required Z3 headers**: Serve the document with `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` (`COOP`/`COEP`). Cross-origin script and WASM assets also require `Cross-Origin-Resource-Policy: cross-origin` (`CORP`) or valid CORS headers (`Access-Control-Allow-Origin`), depending on the request mode.
82
+ - **Fail-fast check & no auto-injected Service Worker**: Importing `@ohtaman/washi` never injects a Service Worker. `m.solve()` and `m.check()` with Z3 reject immediately if a secure context or Cross-Origin Isolation is missing.
83
+
84
+ #### Web Workers & Cancellation (`AbortSignal`)
85
+
86
+ - **Default Workers**: On standard browser origins (`window.origin !== "null"`), HiGHS and Pumpkin default to Web Workers (`useWorker: true`). On opaque origins (`window.origin === "null"`, such as `file://` pages or sandboxed iframes without `allow-same-origin`), both default to `useWorker: false`.
87
+ - **Worker cancellation**: Pre-solve cancellation (`signal.aborted`) works on all solvers, and `{ signal }` terminates in-flight HiGHS and Pumpkin Workers immediately.
88
+ - **Main-thread & Node.js cancellation**: HiGHS checks `signal` during `onProgress` callbacks, Pumpkin polls `signal` at search checkpoints, and GLPK/Z3 only check `signal` before starting.
89
+
90
+ #### Solver Capabilities, Options, & Validation Errors
91
+
92
+ | Solver | Problem Classes | Accepted Options | Throws On |
93
+ | --- | --- | --- | --- |
94
+ | **HiGHS** *(default)* | Linear (`LP`), mixed-integer (`MIP`), and convex quadratic (`QP`) | `timeLimit`, `presolve`, `relativeGap`, `absoluteGap`, `outputFlag`, `relax`, `useWorker`, `wasmUrl`, `signal`, `onProgress` | `threads`, `verbose` (use `outputFlag`), unknown keys, MIQP (quadratic objective with integer/binary/boolean variables) |
95
+ | **Pumpkin** | Constraint Programming (`CP`), bounded discrete `unsatCore` | `timeLimit`, `useWorker`, `wasmUrl`, `signal`, `onProgress` | `relax: true`, `presolve`, `relativeGap`, `absoluteGap`, `threads`, `verbose`, `outputFlag`, unknown keys, `Continuous` variables, unbounded variables or bounds outside `[-(2^30 - 1), 2^30 - 1]`, fractional coefficients/RHS, `QuadExpr` |
96
+ | **Z3** | Satisfiability Modulo Theories (`SMT`), continuous/discrete `unsatCore` | `signal`, `onProgress`, `z3JsUrl`, `z3WasmUrl` | `relax: true`, `useWorker: true`, `timeLimit`, `presolve`, `relativeGap`, `absoluteGap`, `threads`, `verbose`, `outputFlag`, unknown keys, `QuadExpr`, variable `initialValue` |
97
+ | **GLPK** | `LP`, `MIP` | `timeLimit`, `presolve`, `relativeGap`, `verbose`, `relax`, `signal`, `onProgress` | `useWorker: true`, `absoluteGap`, `threads`, `outputFlag` (use `verbose`), unknown keys, `QuadExpr`, variable `initialValue` |
98
+
99
+ Warm-start hints live on variables (`initialValue`), not `solve()`/`check()` options; see Step 1 below for solver support.
84
100
 
85
101
  ---
86
102
 
@@ -98,7 +114,7 @@ const x = m.continuous("x", { lb: 0, ub: 100 });
98
114
  const y = m.continuous("y", { lb: 0, ub: 100 });
99
115
  const n = m.integer("n", { lb: 0, ub: 10 });
100
116
  const b = m.binary("b");
101
- const flag = m.bool("flag"); // Propositional boolean (auto 0-1 MIP on HiGHS/GLPK, native LCG/SMT on Pumpkin/Z3)
117
+ const flag = m.bool("flag"); // Propositional boolean (auto 0-1 MIP on HiGHS/GLPK, native CP/SMT on Pumpkin/Z3)
102
118
 
103
119
  // Indexed variable containers:
104
120
  // - Numeric dimension -> Array
@@ -109,30 +125,40 @@ const byItem = m.integer(["desk", "chair"] as const, { lb: 0 }); // Record<"desk
109
125
  const mixed = m.binary(["A", "B"] as const, 3); // Record<"A" | "B", Var[]>
110
126
  ```
111
127
 
112
- - **Optional Primal Initial Values (`initialValue?: number`)**:
113
- - Numeric variable constructors (`m.continuous`, `m.integer`, `m.binary`, and `new Var`) and the mutable `v.initialValue` property accept an optional finite primal hint (validated with tolerance `1e-6` against bounds `[lb, ub]` and integer/binary domains), kept distinct from the solved `v.value`.
114
- - A start may be complete or partial (e.g., transferred by stable variable names when rebuilding a MIP model). Supplying `initialValue` is a hint only—it does **not** fix the variable, add a hard constraint, or guarantee solver acceptance or a runtime speedup.
115
- - Supported by **HiGHS** and **Pumpkin** (`supportsWarmStart: true`); solvers without warm-start support (**GLPK**, **Z3**) throw an error if any variable has `initialValue !== undefined`.
128
+ - **Primal hints**: Numeric variable constructors and `v.initialValue` accept a finite starting value, validated against `[lb, ub]` and checked for integrality (tolerance `1e-6`), and kept distinct from the solved `v.value`.
129
+ - **Hint semantics**: Complete or partial warm starts do not fix variables, add hard constraints, or guarantee solver acceptance or speedup.
130
+ - **Warm-start support**: Supported by HiGHS and Pumpkin (`supportsWarmStart: true`). GLPK and Z3 throw if any variable has `initialValue` set.
116
131
 
117
132
  ### Step 2: Build Expressions (`expr`, `sum`, `dot`, `max`, `min`, `abs`, `at`)
118
133
 
119
- - **Unified `expr` template tag**:
120
- - Linear expression (`LinExpr`): `` expr`30 * ${x} + 50 * ${n} - 10` ``, `` expr`dot(${profit}, ${byItem}) - 20 * ${b}` ``, `` expr`sum((${price} - ${cost}) * ${byItem})` ``
121
- - Piecewise-linear & element primitives (`max`, `min`, `abs`, `at`, usable inside `expr` or standalone): `` expr`max(${vec}) + sum(abs(${vec} - ${target}))` ``, `` expr`max(abs(${pred} - ${actual}))` ``, `` expr`at(${costs}, ${idx})` `` (0-based integer `idx`, automatically enforcing $0 \le \text{idx} < \text{costs.length}$). On HiGHS/GLPK, convex directions (`minimize` or `<=` on `max`/`abs`, `maximize` or `>=` on `min`) lower to pure continuous LP epigraphs with zero binary variables, while non-convex/equality contexts use exact bounded MIP formulations (finite bounds required); Pumpkin lowers natively (`maximum`/`minimum`/`absolute`/`element`) and Z3 uses native `If` (ITE).
122
- - Quadratic expression (`QuadExpr`): `` expr`${x}^2 + 2 * ${x} * ${y} + ${y}^2` ``, `` expr`sum((${vec} - ${target})^2)` `` (supported for convex QP objectives on purely continuous models using `m.continuous`; built-in HiGHS does not support MIQP models containing integer, binary, or boolean variables).
123
- - Constraint (`Constraint`): `` expr`${x} + 2 * ${n} <= 40` ``, `` expr`sum(${byItem}) <= 100` `` (supports `<=`, `>=`, `==`, `=`, plus discrete integer-only `<`, `>`, `!=`).
124
- - **Aggregations & Element-Wise Container Arithmetic**:
125
- - `sum(containerOrItems, mapper?)` (usable inside `` expr`sum(...)` `` or standalone `sum(...)`) sums a 1D/2D `Array`, `Iterable`, or plain `Record` of `Var` / `LinExpr` / `number` (without needing `Object.values(record)`), or maps over items/counts via `sum(items, (item, i) => ...)`. Inside `` expr`sum(...)` ``, element-wise container arithmetic (`+`, `-`, `*`, `/`, `^2`) and `abs(...)` mapping are also supported.
126
- - `dot(a, b)` (usable inside `` expr`dot(${a}, ${b})` `` or standalone `dot(a, b)`) computes the inner product of matching 1D arrays, 2D arrays (`number[][]` / `Var[][]`, computing the Frobenius inner product $\sum_{i,j} A_{i,j} B_{i,j}$), plain records (`Record<string, ...>`), or mixed Array/Record containers in either operand order.
127
- - **Fluent methods**:
128
- - Arithmetic (on `LinExpr` and `QuadExpr`; `Var` supports `.add()`, `.sub()`, `.mul()`, `.neg()`): `.add(other)`, `.sub(other)`, `.mul(other)`, `.div(scalar)`, `.neg()`
129
- - Comparisons (on `Var`, `LinExpr`, and `QuadExpr`): `.le(rhs, name?)`, `.ge(rhs, name?)`, `.eq(rhs, name?)`, plus discrete integer-only `.lt(rhs, name?)`, `.gt(rhs, name?)`, `.ne(rhs, name?)` (Continuous / fractional operands throw immediately)
130
- - CP global constraints (`BoolExpr` predicates composable with logical operators): `distinct(...args)` (pairwise `!=` on HiGHS/GLPK, `all_different` via pairwise `binary_not_equals` on Pumpkin `0.5.0`, `ctx.Distinct` on Z3), `disjoint(tasks)` (`{ start, duration }`, native `disjunctive_strict` Vilím edge-finding on Pumpkin), `cumulative(tasks, capacity)` (`{ start, duration, demand }`, native `cumulative` time-table on Pumpkin; MIP time-indexed formulation enforces a horizon memory guard recommending `{ solver: "pumpkin" }`), and `allowed(vars, tuples)` (`table` / `negative_table` on Pumpkin)
131
- - Boolean logic (on `BoolVar`, `BoolExpr`, and `Constraint`): standalone `and(...)`, `or(...)`, `not(...)`, `implies(a, b)`, `xor(a, b)` and fluent `.and(...)`, `.or(...)`, `.not()`, `.implies(...)`, `.xor(...)`—solved natively on Z3 and Pumpkin (bounded integers) and automatically linearized to 0-1 MIP on HiGHS/GLPK (negated comparison `Constraint`s in `implies` antecedents, `not`, or `xor` use exact $\pm 1$ shifts over integer-valued `Integer`/`Binary` expressions; `Continuous` or non-integer negated `Constraint`s throw on MIP solvers—use `{ solver: "z3" }`, or write ``or(expr`... >= ... + eps`, ...)`` / `m.bool()`)
134
+ #### Unified `expr` Template Tag
135
+
136
+ | Form | Examples | Notes |
137
+ | --- | --- | --- |
138
+ | Linear (`LinExpr`) | `` expr`30 * ${x} + 50 * ${n} - 10` ``, `` expr`dot(${profit}, ${byItem}) - 20 * ${b}` `` | Also supports `` expr`sum((${price} - ${cost}) * ${byItem})` ``. |
139
+ | Piecewise & element | `` expr`max(${vec}) + sum(abs(${vec} - ${target}))` ``, `` expr`at(${costs}, ${idx})` `` | `at()` enforces `0 <= idx < costs.length` on 0-based integer `idx`. Convex uses (e.g., minimizing `max`/`abs`) stay pure LP on HiGHS/GLPK; non-convex contexts require finite bounds. |
140
+ | Quadratic (`QuadExpr`) | `` expr`${x}^2 + 2 * ${x} * ${y} + ${y}^2` ``, `` expr`sum((${vec} - ${target})^2)` `` | Supported on HiGHS for convex QP objectives over continuous variables (`m.continuous`); MIQP and quadratic constraints are rejected, and other solvers reject `QuadExpr`. |
141
+ | Constraint (`Constraint`) | `` expr`${x} + 2 * ${n} <= 40` ``, `` expr`sum(${byItem}) <= 100` `` | Supports `<=`, `>=`, `==`, `=`, plus integer-only `<`, `>`, `!=`. |
142
+
143
+ #### Aggregations & Fluent Methods
144
+
145
+ - **`sum(containerOrItems, mapper?)`**: Sums a 1D/2D `Array`, `Iterable`, or plain object (`Record`) of variables, expressions, or numbers, optionally transforming each item with `mapper`. Inside `` expr`sum(...)` ``, element-wise `+`, `-`, `*`, `/`, `^2`, and `abs(...)` also work.
146
+ - **`dot(a, b)`**: Computes the inner product of matching 1D arrays, 2D arrays (Frobenius inner product $\sum_{i,j} A_{i,j} B_{i,j}$), plain objects, or mixed `Array`/`Record` containers.
147
+ - **Fluent arithmetic & comparisons**: `.add()`, `.sub()`, `.mul()`, `.div(scalar)`, `.neg()`, plus `.le()`, `.ge()`, `.eq()`, and integer-only `.lt()`, `.gt()`, `.ne()` (all taking `(rhs, name?)`; continuous/fractional operands throw on strict/not-equal comparisons).
148
+
149
+ #### CP Global Constraints & Boolean Logic
150
+
151
+ | Helper | Purpose | Solver Lowering |
152
+ | --- | --- | --- |
153
+ | `distinct(...args)` | All variables take pairwise distinct values | Native on Pumpkin and Z3; pairwise `!=` on HiGHS/GLPK. |
154
+ | `disjoint(tasks)` | Non-overlapping intervals (`{ start, duration }`) | Native scheduling propagator on Pumpkin; linearized on MIP solvers. |
155
+ | `cumulative(tasks, capacity)` | Shared resource capacity (`{ start, duration, demand }`) | Native propagator on Pumpkin; MIP time-indexed encoding enforces a horizon memory guard. |
156
+ | `allowed(vars, tuples)` | Restrict variable tuples to an allowed table | Native table propagator on Pumpkin; linearized on MIP solvers. |
157
+ | `and`, `or`, `not`, `implies`, `xor` | Composable boolean logic (standalone or fluent) | Native on Pumpkin and Z3; linearized to 0-1 MIP on HiGHS/GLPK (negated continuous constraints throw on MIP—use `{ solver: "z3" }` or reformulate with boolean variables). |
132
158
 
133
159
  ### Step 3: Register Objective & Constraints on the Model
134
160
 
135
- Constructing an `expr` or `.le()` object does **not** attach it to the model until you pass it to `m.constraint(...)` or `m.objective(...)` (when `options.M` is omitted in `m.indicator()`, HiGHS/GLPK use tight derived Big-M and preserve `toLpString()`, while Pumpkin lowers natively via `implied_by` and Z3 via `ctx.Implies` unless the returned `Constraint` row is subsequently mutated):
161
+ Constructing an expression or constraint via `expr` or `.le()` does **not** attach it to the model until you call `m.constraint(...)` or `m.objective(...)`. In `m.indicator()`, omitting `options.M` derives tight Big-M bounds for MIP solvers while keeping native indicator lowering on Pumpkin and Z3:
136
162
 
137
163
  ```ts
138
164
  // Set objective using maximize() or minimize()
@@ -141,28 +167,35 @@ m.objective(maximize(expr`30 * ${x} + 50 * ${n}`));
141
167
  // Register constraints on the model (returns the registered Constraint / BoolExpr or array)
142
168
  const limit = m.constraint(expr`${x} + 2 * ${n} <= 40`, "resource_limit");
143
169
 
144
- // Indicator constraint (MIP Big-M reformulation: b === 1 => x <= 50)
170
+ // Indicator constraint (b === 1 => x <= 50; Big-M on MIP, native on Pumpkin/Z3)
145
171
  m.indicator(b, expr`${x} <= 50`, { activeValue: 1, name: "cap_when_b" });
146
172
  ```
147
173
 
148
174
  ### Step 4: Execute (`solve` or `check`) & Verify (`verify`)
149
175
 
150
- - **Optimization (`await m.solve(options?)`)**:
151
- - Returns `SolverStatus` (`"Optimal"`, `"Feasible"`, `"Infeasible"`, `"Unbounded"`, `"TimeLimit"`, `"IterationLimit"`, `"Error"`, `"Unknown"`, `"NotSolved"`, `"Sat"`, or `"Unsat"`). Built-in optimization solvers return the optimization statuses (`"Optimal"`, `"Feasible"`, `"Infeasible"`, `"Unbounded"`, `"TimeLimit"`, `"IterationLimit"`, `"Error"`, `"Unknown"`, `"NotSolved"`), where a time-, iteration-, or solution-limited run (or an interrupted solve) that found a valid primal incumbent returns `"Feasible"`; `"Sat"` and `"Unsat"` are included in `SolverStatus` for satisfiability/custom solver adapters (such as `MockSolver`).
152
- - Read values via `x.value`, `expr`...`.value`, `m.values`, `m.objectiveValue`, `constr.dual`, `constr.slack`, and `x.reducedCost`, and inspect registered entities via `m.variables` (`ReadonlyMap<string, Var | BoolVar>`) and `m.constraints` (`ReadonlyMap<string, Constraint | LogicalConstraint>`).
153
- - Call `m.verify()` after solving to independently verify variable finiteness, variable bounds (`lb`/`ub`), integer/binary/boolean domains, linear constraint residuals, and logical constraints (`VerificationReport`: `{ valid, complete, maxViolation, violations, ... }`). Note that `verify()` checks primal feasibility of variables and constraints; it does not recompute or compare `m.objectiveValue`.
154
- - **Satisfiability & Conflict Diagnosis (`await m.check(options?)`)**:
155
- - Returns `CheckResult` (`{ status: "Sat" | "Unsat" | "Unknown", values: Record<string, number | boolean>, conflicts?: readonly string[], unsatCore?: readonly string[], runTime?: number }`), where `conflicts` is populated when the model is proven `"Unsat"`.
156
- - For models containing linear arithmetic constraints or logical constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`), `m.check()` works with any solver (including the default HiGHS and GLPK via single-solve elastic slack relaxation, automatically linearizing logical constraints into 0-1 MIP formulation) and diagnoses conflicting constraints as `conflicts` (leaving `unsatCore: undefined` for semantic rigor).
157
- - Exact unsatisfiable-core extraction (`result.unsatCore` and `result.conflicts`) is provided when using `{ solver: "z3" }` or `{ solver: "pumpkin" }`. Use `"pumpkin"` (`@ohtaman/washi/solvers/pumpkin`) for bounded-integer/propositional models in environments without `COOP`/`COEP` headers, and use `"z3"` when `Continuous` variables or fractional arithmetic are involved. Because Z3 and Pumpkin assert variable bounds (`lb`/`ub`) and binary `{0, 1}` domains directly while tracking registered constraints, `unsatCore` reports a subset of registered constraint names that conflicts *together with the model's fixed variable bounds/domains* (and is not guaranteed minimal).
158
- - **No concurrent mutation during async solve/check**:
159
- - Mutating variables, constraints, or the objective while `await m.solve()` or `await m.check()` is pending invalidates the in-flight execution and rejects the stale promise.
176
+ #### Optimization (`await m.solve(options?)`)
177
+
178
+ - **Return value**: Returns `SolverStatus` (`"Optimal"`, `"Feasible"`, `"Infeasible"`, `"Unbounded"`, `"TimeLimit"`, `"IterationLimit"`, `"Error"`, `"Unknown"`, `"NotSolved"`, `"Sat"`, or `"Unsat"`).
179
+ - **Status semantics**: Optimization solvers return `"Feasible"` when a limit or abort terminates the solve with a valid primal incumbent. `"Sat"` and `"Unsat"` apply to satisfiability or custom solver adapters.
180
+ - **Reading results**: Check `m.hasPrimalSolution`, then read `x.value`, `` expr`...`.value ``, `m.objectiveValue`, `constr.dual`, `constr.slack`, and `x.reducedCost`. `m.values` (like `m.variables` and `m.constraints`) is a `ReadonlyMap<string, number | boolean>` (use `.get(name)`), unlike `CheckResult.values` and `m.solution.values` (`Record`).
181
+ - **Independent verification**: `m.verify()` checks primal feasibility—finiteness, bounds, integrality, and constraints—returning `VerificationReport` (`{ valid, complete, maxViolation, violations }`) without recomputing `m.objectiveValue`.
182
+
183
+ #### Satisfiability & Conflict Diagnosis (`await m.check(options?)`)
184
+
185
+ - **Return value**: Returns `CheckResult` (`{ status: "Sat" | "Unsat" | "Unknown", values: Record<string, number | boolean>, conflicts?: readonly string[], unsatCore?: readonly string[], runTime?: number }`).
186
+ - **HiGHS & GLPK**: Diagnose linear and logical conflicts in `conflicts` via slack relaxation, leaving `unsatCore` as `undefined`.
187
+ - **Pumpkin & Z3**: Extract an exact unsatisfiable core into both `unsatCore` and `conflicts`. Use Pumpkin for bounded integer/boolean models and Z3 when continuous or fractional constraints are present.
188
+ - **Bounds caveat**: Variable bounds `lb`/`ub` and binary domains are asserted directly, so `unsatCore` reports constraint names that conflict *together with those variable bounds* (not guaranteed minimal).
189
+
190
+ #### Concurrent Mutation Rule
191
+
192
+ - Mutating variables, constraints, or the objective while an `m.solve()` or `m.check()` call is pending invalidates the in-flight run and rejects the stale promise.
160
193
 
161
194
  ---
162
195
 
163
196
  ## 3. Executable Examples
164
197
 
165
- ### Example A: Mixed-Integer Linear Programming (MIP) with Indexed Containers & Solution Validation
198
+ ### Example A: Mixed-Integer Linear Programming (MIP) with Indexed Containers & Solution Verification
166
199
 
167
200
  ```ts
168
201
  import { Model, expr, dot, sum, maximize } from "@ohtaman/washi";
@@ -186,23 +219,25 @@ export async function runMipExample() {
186
219
  });
187
220
 
188
221
  const status = await m.solve();
189
- const report = m.verify();
190
- const values = { desk: qty.desk.value, chair: qty.chair.value };
222
+ const report = m.hasPrimalSolution ? m.verify() : null;
223
+ const values = m.hasPrimalSolution
224
+ ? { desk: qty.desk.value, chair: qty.chair.value }
225
+ : null;
191
226
 
192
227
  return {
193
228
  status,
194
229
  objectiveValue: m.objectiveValue,
195
230
  values,
196
- setup: setup.value,
197
- valid: report.valid,
198
- maxViolation: report.maxViolation,
231
+ setup: m.hasPrimalSolution ? setup.value : null,
232
+ valid: report?.valid ?? false,
233
+ maxViolation: report?.maxViolation ?? null,
199
234
  };
200
235
  }
201
236
  ```
202
237
 
203
238
  ### Example B: Convex Quadratic Programming (QP)
204
239
 
205
- Variable-by-variable products (`${x} * ${y}`) and squares (`${x}^2`) are supported in `expr` for quadratic objectives:
240
+ Products of two variables (`${x} * ${y}`) and squares (`${x}^2`) are supported in `expr` for quadratic objectives:
206
241
 
207
242
  ```ts
208
243
  import { Model, expr, minimize } from "@ohtaman/washi";
@@ -217,14 +252,14 @@ export async function runQpExample() {
217
252
  m.constraint(expr`${x} + ${y} >= 4`, "budget");
218
253
 
219
254
  const status = await m.solve();
220
- const report = m.verify();
255
+ const report = m.hasPrimalSolution ? m.verify() : null;
221
256
 
222
257
  return {
223
258
  status,
224
259
  objectiveValue: m.objectiveValue,
225
- x: x.value,
226
- y: y.value,
227
- valid: report.valid,
260
+ x: m.hasPrimalSolution ? x.value : null,
261
+ y: m.hasPrimalSolution ? y.value : null,
262
+ valid: report?.valid ?? false,
228
263
  };
229
264
  }
230
265
  ```
@@ -248,15 +283,15 @@ export async function runZ3Example() {
248
283
  return {
249
284
  status: unsatResult.status,
250
285
  conflicts: unsatResult.conflicts,
286
+ unsatCore: unsatResult.unsatCore,
251
287
  };
252
288
  }
253
289
  ```
254
290
 
255
- ### Example D: Pumpkin CP Disjunctive Scheduling & Zero-COOP/COEP Unsat Core
291
+ ### Example D: Pumpkin CP Scheduling & Discrete Unsat Core
256
292
 
257
293
  ```ts
258
294
  import { Model, expr, disjoint, distinct, implies, minimize } from "@ohtaman/washi";
259
- import "@ohtaman/washi/solvers/pumpkin";
260
295
 
261
296
  export async function runPumpkinExample() {
262
297
  // Part 1: Bounded-integer CP scheduling with native global propagators
@@ -278,9 +313,15 @@ export async function runPumpkinExample() {
278
313
  cpModel.objective(minimize(expr`${start.paint} + 2`));
279
314
 
280
315
  const status = await cpModel.solve();
281
- const report = cpModel.verify();
282
-
283
- // Part 2: Zero-COOP/COEP unsatCore diagnosis on bounded integers & booleans
316
+ const report = cpModel.hasPrimalSolution ? cpModel.verify() : null;
317
+ const starts = cpModel.hasPrimalSolution
318
+ ? { cut: start.cut.value, weld: start.weld.value, paint: start.paint.value }
319
+ : null;
320
+ const benches = cpModel.hasPrimalSolution
321
+ ? { cut: bench.cut.value, weld: bench.weld.value, paint: bench.paint.value }
322
+ : null;
323
+
324
+ // Part 2: Discrete unsatCore diagnosis on bounded integers & booleans
284
325
  const unsatModel = new Model("DiscreteConflict", { solver: "pumpkin" });
285
326
  const vip = unsatModel.bool("vip");
286
327
  const discount = unsatModel.integer("discount", { lb: 0, ub: 50 });
@@ -293,9 +334,9 @@ export async function runPumpkinExample() {
293
334
  return {
294
335
  status,
295
336
  makespan: cpModel.objectiveValue,
296
- starts: { cut: start.cut.value, weld: start.weld.value, paint: start.paint.value },
297
- benches: { cut: bench.cut.value, weld: bench.weld.value, paint: bench.paint.value },
298
- valid: report.valid,
337
+ starts,
338
+ benches,
339
+ valid: report?.valid ?? false,
299
340
  unsatStatus: unsatResult.status,
300
341
  conflicts: unsatResult.conflicts,
301
342
  unsatCore: unsatResult.unsatCore,
@@ -321,13 +362,13 @@ export function verifyNegativePatterns() {
321
362
  // WRONG: m.objective(maximize(expr`${x} <= 10` as any)); -> throws Error
322
363
  // WRONG: expr`${x} + 1`.add(expr`${y} <= 5` as any); -> throws Error
323
364
 
324
- // 2. DO NOT pass an arithmetic expression without (<=, >=, ==) to m.constraint():
365
+ // 2. DO NOT pass a bare arithmetic expression without a comparison operator (<=, >=, ==, etc.) to m.constraint():
325
366
  // WRONG: m.constraint(expr`${x} + ${y}` as any); -> throws Error
326
367
 
327
- // 3. DO NOT use quadratic terms inside linear constraints:
368
+ // 3. DO NOT use quadratic terms in constraints:
328
369
  // WRONG: expr`${x}^2 <= 10`; -> throws Error ("Quadratic constraints are not supported")
329
370
 
330
- // 4. DO NOT use retired aliases (removed in #59 / #81 / #236 / #273):
371
+ // 4. DO NOT use retired aliases:
331
372
  // - Use `expr` instead of retired `c` template tag
332
373
  // - Use `m.constraint(...)` instead of `m.constrain(...)` or `m.add(...)`
333
374
  // - Use `m.objective(maximize(...))` / `m.objective(minimize(...))` / `m.objective()` instead of `m.maximize(...)` / `m.minimize(...)` / `m.setObjective(...)` / `m.objectiveExpr`
@@ -344,8 +385,6 @@ export function verifyNegativePatterns() {
344
385
 
345
386
  ### Practical OR Modeling Guardrails
346
387
 
347
- - **Prefer inequalities (`>=` / `<=`) over exact equalities (`==`)** for demand coverage and resource limits when objective costs are positive; reserve `==` for physical conservation laws (e.g., flow balance, portfolio weights summing to `1`).
348
- - **Always provide finite `lb` and `ub` bounds** on variables referenced inside `m.indicator(...)` and omit `M` so WaSHI automatically derives the tightest valid Big-M (`m.indicator()` throws if required bounds are infinite and no explicit `M` is provided).
349
- - **Use soft constraints (elastic slack variables)** for non-rigid business targets (e.g., preferred staffing, safety stock, day-off requests) by adding a non-negative slack variable (`lb: 0`) with a tiered objective penalty, reserving hard constraints for physical or legal invariants.
350
-
351
-
388
+ - **Prefer inequalities over equalities**: Use `>=` for demand coverage (when minimizing positive costs) and `<=` for resource caps (when maximizing positive returns). Reserve `==` for conservation laws such as flow balance or weights summing to `1`.
389
+ - **Provide finite bounds for `m.indicator()`**: Give referenced variables finite `lb` and `ub` bounds and omit `M` so WaSHI derives a tight Big-M. Omitting `M` when any referenced variable has an infinite bound throws an error.
390
+ - **Model flexible targets as soft constraints**: Add a non-negative slack variable (`lb: 0`) penalized in the objective for preferences like safety stock or day-off requests. Reserve hard constraints for physical or legal invariants.