@ohtaman/washi 0.8.0 → 0.8.2

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.md +32 -34
  2. package/dist/browser/{__vite-browser-external-rTVKos2U.js → solvers/highs-__vite-browser-external-Dn-83hnF.js} +1 -1
  3. package/dist/browser/{browser-runtime-AG5QFtKf.js → solvers/highs-browser-runtime-0Bgq5ksG.js} +1 -1
  4. package/dist/browser/{loader-i3FnqMes.js → solvers/highs-loader-BLY3wzDH.js} +25 -18
  5. package/dist/browser/{highs-worker.js → solvers/highs-worker.js} +1 -1
  6. package/dist/browser/solvers/highs.js +1414 -0
  7. package/dist/browser/washi.js +1090 -1473
  8. package/dist/browser/washi.min.js +4 -4
  9. package/dist/lib/solvers/glpk.js +34 -32
  10. package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
  11. package/dist/lib/solvers/highs.js +410 -0
  12. package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
  13. package/dist/lib/solvers/pumpkin-node-runtime.js +1 -1
  14. package/dist/lib/solvers/pumpkin-worker.js +1 -1
  15. package/dist/lib/solvers/pumpkin.js +247 -1146
  16. package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
  17. package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
  18. package/dist/lib/solvers/z3.js +125 -123
  19. package/dist/lib/washi.js +2426 -1340
  20. package/dist/types/index.d.ts +1 -2
  21. package/dist/types/index.d.ts.map +1 -1
  22. package/dist/types/modeler/index.d.ts +0 -1
  23. package/dist/types/modeler/index.d.ts.map +1 -1
  24. package/dist/types/modeler/model.d.ts +6 -7
  25. package/dist/types/modeler/model.d.ts.map +1 -1
  26. package/dist/types/modeler/solvers/index.d.ts +2 -1
  27. package/dist/types/modeler/solvers/index.d.ts.map +1 -1
  28. package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
  29. package/docs/examples/diet-sensitivity.md +33 -14
  30. package/docs/examples/ecommerce-coupons.md +17 -9
  31. package/docs/examples/index.md +34 -30
  32. package/docs/examples/knapsack.md +11 -5
  33. package/docs/examples/portfolio-qp.md +21 -8
  34. package/docs/examples/production.md +10 -5
  35. package/docs/examples/project-scheduling.md +25 -12
  36. package/docs/examples/shift-scheduling.md +27 -19
  37. package/docs/examples/smt-security.md +27 -12
  38. package/docs/examples/transportation.md +23 -13
  39. package/docs/examples/traveling-salesperson.md +34 -22
  40. package/docs/examples/unsat-core.md +27 -15
  41. package/docs/examples/vehicle-routing.md +74 -28
  42. package/docs/getting-started/ai-agents.md +129 -90
  43. package/docs/getting-started/coding-agents.md +60 -41
  44. package/docs/getting-started/cross-origin.md +27 -14
  45. package/docs/getting-started/index.md +23 -16
  46. package/docs/getting-started/runtimes.md +70 -40
  47. package/docs/guide/constraint-programming.md +74 -44
  48. package/docs/guide/constraints.md +71 -39
  49. package/docs/guide/decomposition.md +72 -42
  50. package/docs/guide/expressions.md +79 -48
  51. package/docs/guide/formulation-tips.md +46 -27
  52. package/docs/guide/objectives.md +55 -31
  53. package/docs/guide/unsat-core.md +56 -53
  54. package/docs/guide/variables.md +61 -28
  55. package/docs/solvers/custom-solver.md +155 -119
  56. package/docs/solvers/glpk.md +58 -17
  57. package/docs/solvers/highs.md +115 -43
  58. package/docs/solvers/index.md +33 -26
  59. package/docs/solvers/pumpkin.md +71 -63
  60. package/docs/solvers/z3.md +63 -25
  61. package/llms-full.txt +1623 -953
  62. package/llms.txt +125 -93
  63. package/package.json +29 -22
  64. package/skills/washi/SKILL.md +43 -22
  65. package/README.ja.md +0 -248
  66. package/README.zh-CN.md +0 -248
  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
@@ -2,17 +2,17 @@
2
2
 
3
3
  | Problem Class | Solver | Key APIs | Links |
4
4
  | :--- | :--- | :--- | :--- |
5
- | CP / LCG (RCPSP & Unsat Core) | Pumpkin (`@ohtaman/washi/solvers/pumpkin`) | `m.integer()`, `disjoint()`, `cumulative()`, `max()`, `and()`, `m.check()` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=project_scheduling">Playground (Schedule)</a></li><li><a href="https://washi.ohtaman.dev/demo/?preset=project_conflict_unsat">Playground (Conflict)</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/15-project-scheduling-cp.ts">Source Code</a></li><li><a href="/guide/constraint-programming">CP Modeling Guide</a></li></ul> |
5
+ | Constraint Programming (RCPSP) / Unsat Core Diagnosis | Pumpkin (`{ solver: "pumpkin" }`) | `m.integer()`, `disjoint()`, `cumulative()`, `max()`, `and()`, `m.check()` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=project_scheduling">Playground (Schedule)</a></li><li><a href="https://washi.ohtaman.dev/demo/?preset=project_conflict_unsat">Playground (Conflict)</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/15-project-scheduling-cp.ts">Source Code</a></li><li><a href="/guide/constraint-programming">CP Modeling Guide</a></li></ul> |
6
6
 
7
- The **Resource-Constrained Project Scheduling Problem (RCPSP)** models project tasks governed simultaneously by **precedence dependencies**, **unary shared equipment** (disjunctive resource), and **limited renewable team headcount** (cumulative resource).
7
+ The **Resource-Constrained Project Scheduling Problem (RCPSP)** schedules project tasks to minimize the maximum completion time, known as the **makespan**. It balances task precedence order, exclusive single-machine equipment, and limited team headcount at the same time.
8
8
 
9
- Using WaSHI's bundled **Pumpkin** solver (`@ohtaman/washi/solvers/pumpkin`):
10
- 1. Every task needs only **one finite-domain start variable** (`start[task]`), avoiding $O(|T| \cdot H)$ time-indexed binary variables.
11
- 2. When adding tighter maintenance windows or rush shipping deadlines causes infeasibility, `m.check()` extracts the conflicting rule subset (`unsatCore`) client-side with **zero `COOP` / `COEP` headers**.
9
+ Using WaSHI's bundled **Pumpkin** solver (`{ solver: "pumpkin" }`, zero extra imports):
10
+ 1. Each task needs only one integer start variable (`start[task]`), avoiding binary variables for every `(task, hour)` pair.
11
+ 2. When a maintenance window or tight deadline makes the schedule `"Infeasible"`, `m.check()` isolates the conflicting rules (`unsatCore`) on the same model.
12
12
 
13
13
  ## Problem Inputs
14
14
 
15
- We schedule **6 hardware prototype tasks** over a 24-hour window (`crewCapacity = 3` engineers, 1 shared Hardware-in-the-Loop (HIL) calibration rig):
15
+ We schedule **6 hardware prototype tasks** with a start-time horizon of `24` hours (`horizon = 24`). The team has `crewCapacity = 3` engineers and 1 shared test and calibration rig:
16
16
 
17
17
  | Task | Duration | Crew | Dependencies | Shared Rig (`disjoint`) |
18
18
  | :--- | :--- | :--- | :--- | :--- |
@@ -23,7 +23,7 @@ We schedule **6 hardware prototype tasks** over a 24-hour window (`crewCapacity
23
23
  | `calib` | 3h | 1 | `board` | **Yes** |
24
24
  | `test` | 2h | 2 | `assembly`, `firmware`, `calib` | **Yes** |
25
25
 
26
- Notice that ignoring crew capacity gives a naive critical path of `9h` (`chassis 4h -> assembly 3h -> test 2h`), whereas respecting the `crewCapacity = 3` constraint prevents `{chassis, board, assembly}` (2 engineers each) from overlapping, making the true minimum makespan **`12h`**.
26
+ Ignoring the crew limit, `chassis` and `board` can start together at `0h`, giving a `9h` critical path (`chassis 4h -> assembly 3h -> test 2h`). Because `crewCapacity = 3`, `chassis` and `board` each need 2 engineers and cannot overlap (`2 + 2 = 4 > 3`). Running them back-to-back delays `assembly` until `7h`, raising the minimum makespan from `9h` to **`12h`**.
27
27
 
28
28
  ## Implementation in WaSHI
29
29
 
@@ -31,7 +31,6 @@ Notice that ignoring crew capacity gives a naive critical path of `9h` (`chassis
31
31
 
32
32
  ```typescript
33
33
  import { Model, expr, disjoint, cumulative, max, and, minimize } from "@ohtaman/washi";
34
- import "@ohtaman/washi/solvers/pumpkin";
35
34
 
36
35
  async function runProjectScheduling() {
37
36
  const horizon = 24;
@@ -56,7 +55,7 @@ async function runProjectScheduling() {
56
55
  m.constraint(expr`${start.firmware} + 4 <= ${start.test}`, "test_after_firmware");
57
56
  m.constraint(expr`${start.calib} + 3 <= ${start.test}`, "test_after_calib");
58
57
 
59
- // 2. Exclusive HIL / calibration rig & 3-engineer cumulative limit
58
+ // 2. Exclusive shared rig & 3-engineer cumulative limit
60
59
  m.constraint(
61
60
  disjoint(tasks.filter((t) => t.usesRig).map((t) => ({ start: start[t.id], duration: t.duration }))),
62
61
  "single_rig"
@@ -83,6 +82,7 @@ async function runProjectScheduling() {
83
82
  }
84
83
 
85
84
  // 4. Diagnose an impossible rush deadline when the rig is offline for maintenance [0, 6)
85
+ // (restricting firmware and calib to start >= 6; test is already >= 7 via precedence)
86
86
  m.constraint(
87
87
  and(expr`${start.firmware} >= 6`, expr`${start.calib} >= 6`),
88
88
  "rig_maintenance_window"
@@ -101,6 +101,19 @@ runProjectScheduling();
101
101
 
102
102
  ## Practical Notes
103
103
 
104
- - **Why Pumpkin shines here**: Combining `disjoint` (edge-finding) and `cumulative` (time-table propagation) directly on bounded integers lets Pumpkin learn why a schedule bottlenecks (`crew_limit` or `single_rig`) cleanly through Lazy Clause Generation, with zero time-indexed binary variables.
105
- - **Snapshot `m.objectiveValue` before `m.check()`**: Calling `await m.check()` on the same `Model` clears prior `solve()` fields (`m.objectiveValue` becomes `null`), so capture optimization outputs before running feasibility/conflict checks.
106
- - **Client-side `unsatCore` without `COOP` / `COEP`**: Notice that `diag.unsatCore` excludes unrelated `crew_limit` while isolating the rig maintenance (`firmware >= 6`, `calib >= 6`), `assembly -> test` chain (`test >= 7`), unary `single_rig` total of 9h ($\implies \text{completion} \ge 15 > 13$), and `rush_ship_deadline`.
104
+ ### Compact Scheduling with Global Constraints
105
+
106
+ In Constraint Programming, **global constraints** express recurring scheduling patterns directly over groups of variables. Here, `disjoint()` keeps tasks on the shared rig from overlapping, and `cumulative()` caps simultaneous crew usage at `3`. Because start times are bounded integers rather than hourly binary flags, the model stays small even with a longer horizon or finer time units.
107
+
108
+ ### Snapshot `m.objectiveValue` Before `m.check()`
109
+
110
+ Calling `await m.check()` on the same `Model` clears the previous `solve()` outputs, resetting `m.objectiveValue` to `null`. Always store optimization results in local variables before running a conflict check.
111
+
112
+ ### Why the `13h` Rush Deadline Is Infeasible (`unsatCore`)
113
+
114
+ When the maintenance window and `<= 13h` deadline are added, `m.check()` returns `"Unsat"` and isolates the 5 conflicting constraints in `unsatCore`. It excludes unrelated rules such as `crew_limit`, even though crew capacity was the bottleneck in Part 1:
115
+
116
+ 1. `rig_maintenance_window` delays both `firmware` and `calib` until at least `6h`.
117
+ 2. Because `chassis` takes `4h` and `assembly` takes `3h`, `assembly_after_chassis` and `test_after_assembly` delay `test` until at least `7h`.
118
+ 3. Under `single_rig`, the three rig tasks (`firmware` 4h, `calib` 3h, `test` 2h) need `9h` of non-overlapping rig time, and none can start before `6h`.
119
+ 4. As a result, the earliest possible finish is `6 + 9 = 15h`, which conflicts with `rush_ship_deadline` (`<= 13h`).
@@ -2,36 +2,44 @@
2
2
 
3
3
  | Problem Class | Solver | Key APIs | Links |
4
4
  | :--- | :--- | :--- | :--- |
5
- | Binary MIP & SMT Unsat Core | HiGHS + Z3 | `m.binary(staff, days)`, `m.constraint()`, `expr` (`sum`, `dot`), `minimize`, `m.check()` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=shift_scheduling">Playground (Roster)</a></li><li><a href="https://washi.ohtaman.dev/demo/?preset=shift_conflict_unsat">Playground (Conflict)</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/11-shift-scheduling.ts">Source Code</a></li></ul> |
5
+ | Binary MIP & SMT Unsat Core | HiGHS + Z3 | `m.binary(staff, days)`, `m.constraint()`, `expr` (`sum`, `dot`), `minimize`, `m.check()`, `m.unsatCore` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=shift_scheduling">Playground (Roster)</a></li><li><a href="https://washi.ohtaman.dev/demo/?preset=shift_conflict_unsat">Playground (Conflict)</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/11-shift-scheduling.ts">Source Code</a></li></ul> |
6
6
 
7
- Staff shift scheduling is a classic real-world application of Mixed-Integer Programming in SaaS and workforce management tools. However, in real applications, **staff vacation requests frequently collide with minimum coverage or leadership rules**, causing the solver to return `Infeasible`.
7
+ In staff shift scheduling, vacation requests often collide with minimum headcount or senior coverage rules, causing a Mixed-Integer Programming (MIP) solver to return `"Infeasible"`.
8
8
 
9
- This example demonstrates a practical production workflow:
10
- 1. **Try HiGHS MIP Optimization First:** Solve the shift model under the given vacation requests and operational constraints.
11
- 2. **Accept Solution if Optimal:** If a feasible roster is found, display the schedule and minimized payroll cost without unnecessary diagnostic overhead.
12
- 3. **Diagnose with Z3 `unsatCore` Only When Infeasible:** If HiGHS reports `Infeasible`, diagnose the **exact same model and constraints** with Z3 to isolate the conflicting constraint subset (`unsatCore`), pinpointing which day's coverage rules and which staff requests collided.
9
+ This example shows an optimize-then-diagnose workflow on the same model:
10
+ 1. **Optimize with HiGHS first:** Minimize weekly payroll cost under all vacation requests and staffing rules.
11
+ 2. **Use the roster if `"Optimal"`:** Output the schedule and payroll cost with no extra diagnostic step.
12
+ 3. **Diagnose with Z3 if `"Infeasible"`:** Call `model.check({ solver: "z3" })` on the same model to extract the conflicting rule subset (`unsatCore`).
13
13
 
14
14
  > [!IMPORTANT]
15
- > **Vacation Requests are Hard Constraints:**
16
- > In this model, vacation requests are enforced as strict hard constraints (`shift[staff][day] == 0`), not soft constraints with penalty relaxation. When requests collide with mandatory staffing requirements, the model is strictly infeasible.
15
+ > **Vacation Requests Are Hard Constraints:**
16
+ > Each vacation request is modeled as a strict rule (`shift[staff][day] == 0`), not a penalized preference. When requests clash with mandatory coverage, the model is strictly `"Infeasible"`.
17
17
 
18
18
  <ShiftSchedulingDemo />
19
19
 
20
20
  ## Scenario & Rules
21
21
 
22
- We schedule **5 staff members** (`Alice`, `Bob`, `Charlie`, `Diana`, `Evan`) across **7 days** (`Mon`–`Sun`):
22
+ While the interactive widget above expands to 8 staff members, the runnable walkthrough below uses a compact 5-staff × 7-day model.
23
+
24
+ We schedule **5 staff members** across **7 days** from `Mon` to `Sun` — seniors `Alice` (`$220/day`) and `Bob` (`$210/day`), plus `Charlie` (`$160/day`), `Diana` (`$160/day`), and `Evan` (`$150/day`):
23
25
 
24
26
  - **Daily Headcount:** `Mon–Thu`: 3 staff, `Fri`: 4 staff, `Sat`: 3 staff, `Sun`: 2 staff.
25
- - **Senior Duty:** At least 1 senior staff member (`Alice` or `Bob`) must be on duty every day.
27
+ - **Senior Duty:** At least 1 senior staff member (`Alice` or `Bob`) must work every day.
26
28
  - **Work Limit:** Each staff member works at most **5 days** per week.
27
- - **Weekend Premium:** Weekend shifts (`Sat`, `Sun`) incur an extra `+$30` shift premium on top of base daily wage.
29
+ - **Weekend Premium:** `Sat` and `Sun` shifts add `+$30` to the base daily wage.
30
+
31
+ We run two scenarios to show both outcomes:
28
32
 
29
- We evaluate two distinct, named scenarios with different vacation inputs to illustrate the full workflow:
30
- - **Scenario A (Balanced Requests — Feasible):** Alice (Sun), Bob (Mon), Charlie (Sat), Diana (Wed). All constraints can be satisfied simultaneously. HiGHS outputs an optimal roster.
31
- - **Scenario B (Conflicting Requests — Infeasible & Diagnosis):** Alice (Sat), Bob (Sat), Charlie (Sat), Diana (Wed). Because both senior leaders (Alice and Bob) request Saturday off simultaneously, the rule requiring at least 1 senior on duty every day cannot be satisfied. HiGHS reports `Infeasible`, triggering Z3 conflict diagnosis.
33
+ | Scenario | Hard Day-Off Requests | Outcome |
34
+ | :--- | :--- | :--- |
35
+ | **Scenario A (Feasible)** | `Alice (Sun)`, `Bob (Mon)`, `Charlie (Sat)`, `Diana (Wed)` | HiGHS returns `"Optimal"` (`$3,830` weekly payroll). |
36
+ | **Scenario B (Conflict)** | `Alice (Sat)`, `Bob (Sat)`, `Charlie (Sat)`, `Diana (Wed)` | Both seniors request Saturday off, so HiGHS returns `"Infeasible"` and Z3 extracts `unsatCore`. |
32
37
 
33
38
  ## Implementation in WaSHI
34
39
 
40
+ > [!NOTE]
41
+ > **Z3 Prerequisites:** Importing `@ohtaman/washi/solvers/z3` requires the optional `z3-solver` peer dependency (`npm install z3-solver`). Running Z3 in a browser also requires Cross-Origin Isolation (`COOP` / `COEP`) headers — see [Cross-Origin Isolation](../getting-started/cross-origin.md).
42
+
35
43
  <CodeRunner preset="shift_scheduling">
36
44
 
37
45
  ```typescript
@@ -138,7 +146,7 @@ async function runScenario(
138
146
  console.log("Conflicting Constraint Subset (unsatCore):", model.unsatCore);
139
147
  console.log(
140
148
  "Note: unsatCore returns a conflicting subset (minimality/order not guaranteed). " +
141
- "Independent requests like Diana's Wednesday off are excluded.\n"
149
+ "In this run, unrelated requests like Diana's Wednesday off are excluded.\n"
142
150
  );
143
151
  }
144
152
  }
@@ -174,9 +182,9 @@ main();
174
182
 
175
183
  </CodeRunner>
176
184
 
177
- ## Auto-Repairing Conflicts with Soft Constraints (Elastic Requests)
185
+ ## Relaxing Conflicts with Soft Constraints
178
186
 
179
- Once Z3 `unsatCore` diagnoses that `senior_duty_Sat` conflicts with `day_off_Alice_Sat` and `day_off_Bob_Sat`, you can offer managers an automatic repair option by relaxing day-off requests from hard constraints (`shift[staff][day] == 0`) into **soft preferences** penalized in the objective (e.g., `+$500` per overridden day off):
187
+ After Z3 isolates the conflict among `senior_duty_Sat`, `day_off_Alice_Sat`, and `day_off_Bob_Sat`, you can generate a fallback schedule by relaxing the hard day-off constraints (Rule 4) into **soft preferences** that add a `$500` penalty per overridden request:
180
188
 
181
189
  ```typescript
182
190
  // Soft constraint pattern: penalize working on a requested day off by $500
@@ -185,7 +193,7 @@ const requestedShiftVars = dayOffRequests.map((req) => shift[req.staff][req.day]
185
193
  m.objective(minimize(expr`dot(${costMatrix}, ${shift}) + 500 * sum(${requestedShiftVars})`));
186
194
  ```
187
195
 
188
- With this soft formulation on Scenario B, HiGHS automatically finds a valid roster that honors 3 of the 4 requests (`Alice (Sat)`, `Charlie (Sat)`, and `Diana (Wed)`) and overrides only `Bob (Sat)`—choosing Bob over Alice because Bob's daily wage (`$210`) is `$10` lower than Alice's (`$220`).
196
+ On Scenario B, HiGHS returns `"Optimal"` with an objective value of **`$4,330`** (`$3,830` payroll plus one `$500` penalty). It honors 3 of the 4 requests and overrides only 1 senior request (`Alice (Sat)` in the HiGHS output). Because `Bob` has the lower daily wage, the cheapest staffing assigns him up to his 5-day limit (`maxShifts = 5`) and `Alice` to the remaining 2 senior days. Overriding either `Alice (Sat)` or `Bob (Sat)` therefore yields the exact same total cost of `$4,330`.
189
197
 
190
198
  > [!TIP]
191
- > **Diagnosing `unsatCore` Without `COOP` / `COEP` Headers**: Because every variable in this roster model is a 0-1 binary (`m.binary(...)`) with integer coefficients, you can also run `await model.check({ solver: "pumpkin" })` (after `import "@ohtaman/washi/solvers/pumpkin"`) to extract `unsatCore` in standard browser environments without `COOP` / `COEP` headers or external peer dependencies.
199
+ > This model uses only binary variables (`m.binary()`) and constraints with integer coefficients. You can also extract `unsatCore` via `await model.check({ solver: "pumpkin" })` out of the box without installing `z3-solver` or adding extra imports.
@@ -4,20 +4,25 @@
4
4
  | :--- | :--- | :--- | :--- |
5
5
  | Propositional Logic & SMT | Z3 (`@ohtaman/washi/solvers/z3`) | `m.bool()`, `m.integer()`, `implies()`, `m.constraint()`, `expr`, `m.check()` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=smt_security">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/04-smt-security-rules.ts">Source Code</a></li></ul> |
6
6
 
7
- Satisfiability Modulo Theories (SMT) combines propositional logic (Boolean SAT) with first-order theories (linear integer arithmetic, real inequalities).
7
+ **Satisfiability Modulo Theories (SMT)** combines Boolean logic with arithmetic inequalities such as integer bounds and linear comparisons.
8
8
 
9
- This example demonstrates how to formally verify and deduce system states in an IoT home security system using WaSHI and the Z3 solver engine.
9
+ This example verifies safety rules and deduces system states for a smart-home security system using WaSHI and Z3.
10
10
 
11
11
  ## The Scenario
12
12
 
13
- We model a security rule system with sensor readings and logic rules:
14
- 1. When ambient light $\le 50$, it implies night time (`isNight`).
15
- 2. When motion is detected at night and the alarm is armed, the siren must sound.
16
- 3. If the alarm is armed, the front door must never be unlocked.
17
- 4. When motion is detected at night, comfort lights should turn on.
13
+ We model a security rule system driven by sensor readings and logical policies:
14
+ 1. When ambient light (`luxLevel`) is at most `50 lux`, the system enters night mode (`isNight`).
15
+ 2. When motion (`motionDetected`) is detected at night (`isNight`) while the alarm is armed (`alarmArmed`), the siren (`sirenActive`) must sound.
16
+ 3. While the alarm is armed (`alarmArmed`), the front door (`frontDoorUnlocked`) must stay locked.
17
+ 4. When motion (`motionDetected`) is detected at night (`isNight`), comfort lights (`lightsOn`) turn on.
18
+
19
+ Given the observed sensor state — `luxLevel <= 20`, `alarmArmed`, and `motionDetected` — we first deduce the resulting system state. We then formally prove that under these readings, the siren (`sirenActive`) cannot remain off.
18
20
 
19
21
  ## Implementation in WaSHI
20
22
 
23
+ > [!NOTE]
24
+ > **Z3 Prerequisites:** Importing `@ohtaman/washi/solvers/z3` requires the optional `z3-solver` peer dependency (`npm install z3-solver`). Running Z3 in a browser also requires Cross-Origin Isolation (`COOP` / `COEP`) headers — see [Cross-Origin Isolation](../getting-started/cross-origin.md).
25
+
21
26
  <CodeRunner preset="smt_security">
22
27
 
23
28
  ```typescript
@@ -59,7 +64,7 @@ async function verifySecurityRules() {
59
64
  m.constraint(motionDetected, "sensor_motion_triggered");
60
65
 
61
66
  // Check satisfiability and deduce state
62
- const res = await m.check({ solver: "z3" });
67
+ const res = await m.check();
63
68
 
64
69
  console.log(`Status: ${res.status}`);
65
70
  console.log(`Siren Active : ${sirenActive.value}`);
@@ -70,7 +75,7 @@ async function verifySecurityRules() {
70
75
  // 4. Formal Safety Verification (Counterexample Search):
71
76
  // Prove that the siren CANNOT remain off under these sensor readings
72
77
  m.constraint(not(sirenActive), "counterexample_siren_off");
73
- const proof = await m.check({ solver: "z3" });
78
+ const proof = await m.check();
74
79
  console.log(`Can siren stay off? ${proof.status} (Proven safe when Unsat)`);
75
80
  console.log(`Active proof core : ${(proof.conflicts ?? []).join(", ")}`);
76
81
  }
@@ -82,6 +87,16 @@ verifySecurityRules();
82
87
 
83
88
  ## Practical Notes
84
89
 
85
- - **Proof by Refutation (Counterexample Search)**: A single `Sat` check shows that *a* valid assignment exists. To formally prove that a safety property $P$ (such as `sirenActive`) **must** hold in *every* valid state, assert its negation `not(P)` and verify that `m.check()` returns `"Unsat"`. If it returns `"Sat"`, the solver's variable values give you a concrete counterexample (security loophole).
86
- - **One-Way Implication (`implies`) vs. Equivalence**: In classical logic, `` implies(expr`${luxLevel} <= 50`, isNight) `` only constrains `isNight` when `luxLevel <= 50`. During daytime (`luxLevel > 50`), `isNight` is unconstrained ("open-world" assumption) and could be assigned either `true` or `false` unless you also add the converse rule `` implies(expr`${luxLevel} >= 51`, not(isNight)) ``.
87
- - **Running Without `COOP` / `COEP` Headers (`solver: "pumpkin"`)**: Because all variables in this model are propositional `BoolVar`s and bounded integers (`luxLevel` in `[0, 1000]`), the exact same deduction and counterexample `unsatCore` proof works out of the box with bundled `@ohtaman/washi/solvers/pumpkin` (`m.check({ solver: "pumpkin" })`) without `COOP` / `COEP` headers or `z3-solver`.
90
+ ### Proof by Refutation (Counterexample Search)
91
+
92
+ A single `"Sat"` result only shows that at least one valid assignment exists. To prove that a safety property `P` (such as `sirenActive`) always holds, add its negation `not(P)` and call `m.check()`. If the solver returns `"Unsat"`, no counterexample exists; if it returns `"Sat"`, the variable values show a concrete loophole.
93
+
94
+ In this example, the first check returns `"Sat"` with `sirenActive = true`, `lightsOn = true`, `isNight = true`, and the front door locked. Adding `not(sirenActive)` produces `"Unsat"` with a 6-rule proof core, automatically excluding the unrelated `lock_safety_rule` and `comfort_lights`.
95
+
96
+ ### One-Way Implication (`implies`) vs. Equivalence
97
+
98
+ The rule `` implies(expr`${luxLevel} <= 50`, isNight) `` only constrains `isNight` when `luxLevel <= 50` is true. When `luxLevel > 50`, `isNight` is unconstrained and may be assigned either `true` or `false`. To enforce an exact two-way equivalence, also add the converse rule `` implies(isNight, expr`${luxLevel} <= 50`) `` (or its logically equivalent inverse, `` implies(expr`${luxLevel} >= 51`, not(isNight)) ``).
99
+
100
+ ### Alternative Solver for Discrete Models
101
+
102
+ This model contains only `BoolVar` variables and bounded integers (`luxLevel` in `[0, 1000]`). As a result, the same deduction and counterexample proof also work out of the box with bundled Pumpkin via `m.check({ solver: "pumpkin" })`.
@@ -2,26 +2,26 @@
2
2
 
3
3
  | Problem Class | Solver | Key APIs | Links |
4
4
  | :--- | :--- | :--- | :--- |
5
- | Linear Programming (LP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr` (`sum`, `dot`), `minimize` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=transportation">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts">Source Code</a></li></ul> |
5
+ | Linear Programming (LP) | HiGHS (default) | `m.continuous()`, `m.constraint()`, `expr` (`sum`, `dot`), `minimize`, `constr.dual` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=transportation">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/09-transportation-problem.ts">Source Code</a></li></ul> |
6
6
 
7
- The transportation problem is one of the most fundamental network optimization models: determine how many units to ship from each supply origin (factory) to each destination (store) to minimize total shipping cost while respecting factory supply limits and meeting store demands.
7
+ The **transportation problem** decides how many units to ship from each factory to each store. The goal is to minimize total shipping cost while respecting factory supply limits and meeting every store's demand.
8
8
 
9
- This example demonstrates how to construct a **2D matrix of decision variables** using `m.continuous(factories, stores)` and write aggregated constraints declaratively via `dot()` and `m.constraint(expr`...`)`.
9
+ This example builds a 2D decision-variable matrix with `m.continuous(factories, stores)`, writes the total cost objective with `dot()`, and expresses the row and column supply/demand constraints with `sum()` and ``m.constraint(expr`...`)``.
10
10
 
11
11
  ## Problem Inputs
12
12
 
13
- We have **3 factories** (`Tokyo`, `Nagoya`, `Osaka`) shipping to **4 regional stores** (`North`, `East`, `West`, `South`):
13
+ Three factories (`Tokyo`, `Nagoya`, `Osaka`) ship to four regional stores: `North`, `East`, `West`, and `South`.
14
14
 
15
- | Factory \ Store | North ($/unit) | East ($/unit) | West ($/unit) | South ($/unit) | Supply Capacity |
15
+ | Factory / Store | North ($/unit) | East ($/unit) | West ($/unit) | South ($/unit) | Supply Capacity |
16
16
  | :--- | :---: | :---: | :---: | :---: | :---: |
17
17
  | **Tokyo** | $4 | $2 | $7 | $8 | **120** units |
18
18
  | **Nagoya** | $6 | $4 | $3 | $5 | **100** units |
19
19
  | **Osaka** | $9 | $7 | $2 | $3 | **80** units |
20
- | **Store Demand** | **70** units | **90** units | **60** units | **60** units | Total: 280 / 300 |
20
+ | **Store Demand** | **70** units | **90** units | **60** units | **60** units | Demand 280 / Supply 300 |
21
21
 
22
22
  ## Mathematical Formulation
23
23
 
24
- Let $x_{f, s} \ge 0$ be the quantity shipped from factory $f \in F$ to store $s \in S$, and $c_{f, s}$ be the unit shipping cost.
24
+ Let $F$ be the set of factories, $S$ be the set of stores, $\text{Supply}_f$ be factory $f$'s supply capacity, $\text{Demand}_s$ be store $s$'s demand, $x_{f, s} \ge 0$ be the quantity shipped from $f \in F$ to $s \in S$, and $c_{f, s}$ be the unit shipping cost.
25
25
 
26
26
  $$\begin{aligned}
27
27
  \text{Minimize} \quad & \sum_{f \in F} \sum_{s \in S} c_{f,s} \, x_{f,s} \\
@@ -93,10 +93,10 @@ async function solveScenario(label: string, cap: typeof supplies) {
93
93
  }
94
94
 
95
95
  async function runTransportation() {
96
- // Scenario A: Baseline capacities ($920)
96
+ // Scenario A: Baseline capacities (Optimal: $880)
97
97
  await solveScenario("Scenario A: Baseline", supplies);
98
98
 
99
- // Scenario B: Tokyo capacity reduced (120 -> 80) due to maintenance ($1,000)
99
+ // Scenario B: Tokyo reduced (120 -> 80); Nagoya (100 -> 120) & Osaka (80 -> 100) expanded (Optimal: $940)
100
100
  await solveScenario("Scenario B: Tokyo Maintenance", {
101
101
  Tokyo: 80,
102
102
  Nagoya: 120,
@@ -111,7 +111,17 @@ runTransportation();
111
111
 
112
112
  ## Practical Notes
113
113
 
114
- - **Interpreting Supply & Demand Shadow Prices (`.dual`)**:
115
- - **`demand_s.dual` ($\ge 0$)**: The marginal delivered cost of supplying 1 additional unit to store $s$.
116
- - **`supply_f.dual` ($\le 0$)**: How much total network shipping cost would decrease if factory $f$'s capacity were expanded by 1 unit. In Scenario B, when Tokyo is constrained at 80 units, `supply_Tokyo.dual` becomes negative (`-$2/u`), indicating that each extra unit of capacity in Tokyo saves \$2 by avoiding rerouting through Nagoya.
117
- - **Total Supply vs. Total Demand ($\sum \text{Supply}_f \ge \sum \text{Demand}_s$)**: If store demands exceed aggregate factory capacity, the hard demand constraints become `"Infeasible"`. In production logistics systems, add an elastic "spot-carrier / backorder" variable $u_s \ge 0$ to each store's demand constraint ($\sum_f x_{f,s} + u_s \ge \text{Demand}_s$) with a high penalty cost so the solver allocates scarce inventory optimally rather than failing.
114
+ ### Supply & Demand Shadow Prices (`.dual`)
115
+
116
+ In a minimization LP, each constraint's **shadow price** (`.dual`) measures how much total cost changes when its right-hand side increases by 1 unit:
117
+
118
+ - **`demand_s.dual` ($\ge 0$):** Marginal delivered cost of supplying 1 extra unit to store $s$.
119
+ - **`supply_f.dual` ($\le 0$):** Marginal change in total shipping cost when factory $f$'s capacity increases by 1 unit (a negative value indicates cost savings).
120
+
121
+ Scenario A reaches an optimal cost of `$880`, and Scenario B reaches `$940`. In both scenarios, `Tokyo` is already at full capacity with `supply_Tokyo.dual = -$2/unit`. Each extra unit of capacity in Tokyo saves `$2` by replacing more expensive shipments from Nagoya. `Osaka` is also at its supply limit with a shadow price of `-$1/unit`.
122
+
123
+ ### Handling Supply Shortages
124
+
125
+ Hard demand constraints require total supply capacity to cover total demand ($\sum_{f \in F} \text{Supply}_f \ge \sum_{s \in S} \text{Demand}_s$). If total demand exceeds total factory capacity, HiGHS returns `"Infeasible"`.
126
+
127
+ To avoid hard failures during shortages, add a non-negative spot-carrier or backorder variable $u_s \ge 0$ to each store's demand constraint ($\sum_{f \in F} x_{f,s} + u_s \ge \text{Demand}_s$) and add a high penalty cost for $u_s$ to the objective. This lets the solver allocate scarce supply capacity optimally across stores.
@@ -4,15 +4,15 @@
4
4
  | :--- | :--- | :--- | :--- |
5
5
  | Combinatorial OR / Benders | HiGHS (default) | `m.solveBenders()`, `subproblem`, `m.binary()`, `m.constraint()`, `expr` | <ul><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts">Source Code</a></li><li><a href="/guide/decomposition">Decomposition Guide</a></li></ul> |
6
6
 
7
- The **Traveling Salesperson Problem (TSP)** seeks the shortest closed tour that visits every city in a given set once and returns to the starting city.
7
+ The **Traveling Salesperson Problem (TSP)** finds the shortest closed tour that visits every city once and returns to the starting city.
8
8
 
9
- In the **Dantzig-Fulkerson-Johnson (DFJ)** formulation, preventing disconnected cycles (**subtours**) requires subtour elimination constraints for every non-empty proper subset of cities $S \subset V$:
9
+ Let $V$ be the set of $n$ cities ($|V| = n$) and $x_{ij} \in \{0, 1\}$ indicate whether the tour travels directly from city $i$ to city $j$. In the **Dantzig-Fulkerson-Johnson (DFJ)** formulation, preventing disconnected cycles called **subtours** requires a subtour elimination constraint for every subset $S \subset V$ with $2 \le |S| \le n - 1$:
10
10
 
11
- $$\sum_{i \in S, j \notin S} x_{ij} \ge 1 \quad \forall S \subset V, \; 2 \le |S| \le |V| - 1$$
11
+ $$\sum_{i \in S, j \notin S} x_{ij} \ge 1 \quad \forall S \subset V, \; 2 \le |S| \le n - 1$$
12
12
 
13
- Because there are $2^n - 2$ subsets, enumerating all subtour constraints upfront is impractical as $n$ grows. With **Benders Decomposition (Lazy Constraint Separation)**, constraints are added only when violated:
14
- 1. **Master Problem**: Solves the degree-assignment relaxation (each city has 1 incoming and 1 outgoing edge).
15
- 2. **Separation Subproblem**: Inspects the candidate solution graph. If disconnected cycles exist, it adds **Benders Feasibility Cuts** eliminating all detected subtours simultaneously (multi-cut separation) and resolves until a single connected tour is obtained.
13
+ Because there are $2^n - n - 2$ such subsets, enumerating all subtour constraints upfront is impractical as $n$ grows. With **Lazy Constraint Separation (combinatorial Benders cuts via `solveBenders()`)**, constraints are added only when violated:
14
+ 1. **Master Problem**: Solves the degree-assignment relaxation, where each city has 1 incoming edge and 1 outgoing edge.
15
+ 2. **Separation Subproblem**: Traces cycles in the master solution. When disconnected cycles appear, it returns **Benders Feasibility Cuts** for all detected subtours at once (multi-cut separation) until a single tour remains.
16
16
 
17
17
  ## Problem Inputs
18
18
 
@@ -31,7 +31,7 @@ We consider **5 cities** on a 2D Euclidean coordinate grid:
31
31
  <CodeRunner>
32
32
 
33
33
  ```typescript
34
- import { Model, expr, minimize } from "@ohtaman/washi";
34
+ import { Model, expr, minimize, type Var } from "@ohtaman/washi";
35
35
 
36
36
  async function runTSP() {
37
37
  const cities = [
@@ -43,7 +43,7 @@ async function runTSP() {
43
43
  ];
44
44
  const n = cities.length;
45
45
 
46
- function dist(i, j) {
46
+ function dist(i: number, j: number): number {
47
47
  const dx = cities[i].x - cities[j].x;
48
48
  const dy = cities[i].y - cities[j].y;
49
49
  return Math.hypot(dx, dy);
@@ -51,8 +51,8 @@ async function runTSP() {
51
51
 
52
52
  // 1. Master Problem: Degree assignment relaxation
53
53
  const master = new Model("TSP_BendersMaster");
54
- const x = {};
55
- const distMatrix = {};
54
+ const x: Record<number, Record<number, Var>> = {};
55
+ const distMatrix: Record<number, Record<number, number>> = {};
56
56
 
57
57
  for (let i = 0; i < n; i++) {
58
58
  x[i] = {};
@@ -71,7 +71,7 @@ async function runTSP() {
71
71
  // Each city must have 1 outgoing and 1 incoming edge
72
72
  for (let i = 0; i < n; i++) {
73
73
  master.constraint(expr`sum(${x[i]}) == 1`, `out_${i}`);
74
- master.constraint(expr`sum(${n}, ${(j) => x[j][i]}) == 1`, `in_${i}`);
74
+ master.constraint(expr`sum(${n}, ${(j: number) => x[j][i]}) == 1`, `in_${i}`);
75
75
  }
76
76
 
77
77
  console.log("Solving TSP with Benders lazy subtour elimination...");
@@ -81,7 +81,7 @@ async function runTSP() {
81
81
  const result = await master.solveBenders({
82
82
  subproblem: () => {
83
83
  // Find active directed edges in the master solution
84
- const succ = {};
84
+ const succ: Record<number, number> = {};
85
85
  for (let i = 0; i < n; i++) {
86
86
  for (let j = 0; j < n; j++) {
87
87
  if (i !== j && x[i][j].value === 1) {
@@ -91,11 +91,11 @@ async function runTSP() {
91
91
  }
92
92
 
93
93
  // Trace connected cycles
94
- const visited = new Set();
95
- const cycles = [];
94
+ const visited = new Set<number>();
95
+ const cycles: number[][] = [];
96
96
  for (let i = 0; i < n; i++) {
97
97
  if (!visited.has(i)) {
98
- const cycle = [];
98
+ const cycle: number[] = [];
99
99
  let curr = i;
100
100
  while (!visited.has(curr)) {
101
101
  visited.add(curr);
@@ -117,7 +117,7 @@ async function runTSP() {
117
117
  const cutEdges = cycle.flatMap((i) => outCities.map((j) => x[i][j]));
118
118
 
119
119
  return {
120
- kind: "feasibility",
120
+ kind: "feasibility" as const,
121
121
  constraint: expr`sum(${cutEdges}) >= 1`,
122
122
  name: `subtour_cut_${cutCounter}`,
123
123
  };
@@ -148,10 +148,22 @@ runTSP();
148
148
 
149
149
  </CodeRunner>
150
150
 
151
- ## Notes
151
+ ## Key Takeaways
152
152
 
153
- - **Lazy Subtour Elimination**: The master problem starts with only the $2n$ degree constraints, and subtour elimination cuts are added on demand when disconnected cycles appear in the master solution.
154
- - **Multi-Cut Separation**: Returning an array of cuts (`cycles.map(...)`) from `subproblem` eliminates all disconnected cycles discovered in the current candidate solution simultaneously, reducing the number of master MIP re-solves.
155
- - **Two Equivalent DFJ Cut Forms**: Because every city has out-degree $\sum_{j \ne i} x_{ij} = 1$, summing over $i \in S$ gives $\sum_{i \in S, j \in S} x_{ij} + \sum_{i \in S, j \notin S} x_{ij} = |S|$. Thus the cut-set inequality $\sum_{i \in S, j \notin S} x_{ij} \ge 1$ used above and the internal-edge inequality $\sum_{i \in S, j \in S} x_{ij} \le |S| - 1$ used in [`14-traveling-salesperson-benders.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts) are algebraically identical.
156
- - **Upfront 2-City Subtour Elimination**: In larger TSP instances, mutual 2-cycles ($i \leftrightarrow j$) are the most frequent initial subtours. Adding the $\binom{n}{2}$ pairwise constraints $x_{ij} + x_{ji} \le 1$ directly to the initial master problem often cuts the number of Benders iterations substantially.
157
- - **Termination Condition**: Returning `null` from `subproblem` indicates that no violated subtour constraints remain.
153
+ This 5-city instance converges in **2 iterations**. In Iteration 1, the assignment relaxation splits the cities into two subtours (`[A -> B]` and `[C -> E -> D]`), and multi-cut separation adds 2 Benders feasibility cuts at once. In Iteration 2, the master problem finds the optimal single tour with total distance `7.236` ($5 + \sqrt{5}$).
154
+
155
+ ### Lazy Subtour Elimination & Multi-Cut Separation
156
+
157
+ The master problem starts with only $2n$ degree constraints, and `subproblem` adds cuts only when disconnected cycles appear. Returning an array of cuts (`cycles.map(...)`) eliminates every subtour in the current candidate at once, reducing master MIP re-solves. Returning `null` stops the loop once a single connected tour is found.
158
+
159
+ ### Two Equivalent DFJ Cut Forms
160
+
161
+ Every city satisfies the out-degree equation $\sum_{j \ne i} x_{ij} = 1$. Summing this identity over all $i \in S$ gives:
162
+
163
+ $$\sum_{i \in S, \, j \in S, \, j \ne i} x_{ij} + \sum_{i \in S, \, j \notin S} x_{ij} = |S|$$
164
+
165
+ Therefore, the cut-set inequality $\sum_{i \in S, j \notin S} x_{ij} \ge 1$ used above is algebraically identical to the internal-edge form $\sum_{i \in S, \, j \in S, \, j \ne i} x_{ij} \le |S| - 1$ used in [`14-traveling-salesperson-benders.ts`](https://github.com/ohtaman/washi/blob/main/examples/node/14-traveling-salesperson-benders.ts).
166
+
167
+ ### Upfront 2-City Subtour Elimination
168
+
169
+ In larger TSP instances, mutual 2-cycles ($i \leftrightarrow j$) are the most frequent early subtours. Adding the $\binom{n}{2}$ pairwise constraints $x_{ij} + x_{ji} \le 1$ ($i < j$) to the initial master problem often cuts the number of Benders iterations substantially.
@@ -4,25 +4,28 @@
4
4
  | :--- | :--- | :--- | :--- |
5
5
  | Infeasibility Diagnosis / Unsat Core | Z3 (`@ohtaman/washi/solvers/z3`) | `m.integer()`, `m.continuous()`, `implies()`, `m.constraint()`, `expr`, `m.check()`, `m.conflicts` | <ul><li><a href="https://washi.ohtaman.dev/demo/?preset=conflict_diagnosis_unsat">Open in Playground</a></li><li><a href="https://github.com/ohtaman/washi/blob/main/examples/node/05-unsat-core-diagnosis.ts">Source Code</a></li></ul> |
6
6
 
7
- When business rules, budgets, and operational policies grow complex, constraints can easily conflict. Because a standard optimization call (`m.solve()`) only reports `"Infeasible"`, WaSHI provides `m.check()` to pinpoint conflicting rules without manual trial-and-error.
7
+ A standard optimization call (`m.solve()`) only reports `"Infeasible"` when constraints clash. Calling `m.check()` returns `"Unsat"` along with conflicting constraint names: SMT/CP solvers such as Z3 and Pumpkin extract an **Unsat Core** (a mutually inconsistent subset), whereas MIP solvers such as HiGHS return an **Elastic Repair Set**.
8
8
 
9
- This example shows how to isolate the conflicting constraint subset using Z3 Unsat Core extraction.
9
+ This example diagnoses a staffing-vs-budget conflict with Z3 and HiGHS and reads the result from `res.conflicts` (also stored on `m.conflicts`). Here Z3 excludes the unrelated rule, though in general a returned Unsat Core is not guaranteed to be minimal.
10
10
 
11
11
  ## The Conflicting Scenario
12
12
 
13
13
  A tech team is staffing a customer project:
14
- 1. Each engineer costs $8,000 against the project budget (`budget_limit`).
14
+ 1. Each engineer costs $8,000, and total staffing cost must stay within the project budget (`budget_limit`).
15
15
  2. The customer requires rush delivery (`rush_required`).
16
16
  3. Rush delivery mandates at least 8 engineers (`rush_staffing_rule`).
17
- 4. The board has imposed a strict budget cap of $50,000 (`strict_board_budget_cap`).
18
- 5. Labor law requires at least 1 employee on staff (`minimum_one_employee`).
17
+ 4. The board sets a strict budget cap of $50,000 (`strict_board_budget_cap`).
18
+ 5. Labor law requires at least 1 engineer on staff (`minimum_one_employee`).
19
19
 
20
- Notice that:
20
+ These rules contradict each other:
21
21
 
22
- $$8 \text{ engineers} \times \$8,000 = \$64,000 > \$50,000 \text{ budget!}$$
22
+ $$8 \text{ engineers} \times \$8,000 = \$64,000 > \$50,000$$
23
23
 
24
24
  ## Implementation in WaSHI
25
25
 
26
+ > [!NOTE]
27
+ > **Z3 Prerequisites:** Importing `@ohtaman/washi/solvers/z3` requires the optional `z3-solver` peer dependency (`npm install z3-solver`). Running Z3 in a browser also requires Cross-Origin Isolation (`COOP` / `COEP`) headers — see [Cross-Origin Isolation](../getting-started/cross-origin.md).
28
+
26
29
  <CodeRunner preset="conflict_diagnosis_unsat">
27
30
 
28
31
  ```typescript
@@ -45,7 +48,7 @@ async function diagnoseConflicts() {
45
48
  // Rule 3: Rush delivery requires at least 8 engineers
46
49
  m.constraint(implies(rushDelivery, expr`${engineers} >= 8`), "rush_staffing_rule");
47
50
 
48
- // Rule 4: Board budget cap of $50,000 (Conflict!)
51
+ // Rule 4: Board budget cap of $50,000 (conflicts with Rules 1-3)
49
52
  m.constraint(expr`${budget} <= 50000`, "strict_board_budget_cap");
50
53
 
51
54
  // Rule 5: Innocent bystander rule
@@ -54,12 +57,14 @@ async function diagnoseConflicts() {
54
57
  // Run diagnosis
55
58
  const res = await m.check({ solver: "z3" });
56
59
 
57
- console.log(`Status: ${res.status}`);
58
- console.log("Z3 Unsat Core (scale-invariant):", m.conflicts);
60
+ console.log(`Status: ${res.status}`); // Status: Unsat
61
+ console.log("Z3 Unsat Core (scale-invariant):", res.conflicts); // also available via m.conflicts
62
+ // ["budget_limit", "rush_required", "rush_staffing_rule", "strict_board_budget_cap"]
59
63
 
60
- // Built-in HiGHS can also diagnose conflicts via single-solve L1 elastic slack relaxation:
64
+ // Built-in HiGHS can also diagnose conflicts by finding constraints to relax:
61
65
  const highsDiag = await m.check({ solver: "highs" });
62
66
  console.log("HiGHS Elastic Repair Set:", highsDiag.conflicts);
67
+ // ["rush_required"]
63
68
  }
64
69
 
65
70
  diagnoseConflicts();
@@ -69,7 +74,14 @@ diagnoseConflicts();
69
74
 
70
75
  ## Practical Notes
71
76
 
72
- - **Choosing Between Pumpkin, Z3, and HiGHS for Conflict Diagnosis**:
73
- - **Pumpkin (`m.check({ solver: "pumpkin" })`)** is bundled with `@ohtaman/washi/solvers/pumpkin` (zero external dependencies, no `COOP` / `COEP` headers) and extracts scale-invariant `unsatCore` subsets for discrete models where all variables are bounded `Integer`, `Binary`, or `BoolVar` (for example, when `budget` above is modeled with `m.integer("budget", ...)`).
74
- - **Z3 (`m.check({ solver: "z3" })`)** supports `Continuous` variables (like `budget` above) and fractional arithmetic, returning all four rules that jointly form the contradiction (`budget_limit`, `rush_required`, `rush_staffing_rule`, `strict_board_budget_cap`), while excluding the innocent `minimum_one_employee` rule.
75
- - **HiGHS (`m.check({ solver: "highs" })`)** solves a single $L_1$ elastic slack minimization problem ($\min \sum s_i$). Because relaxing `rush_staffing_rule` (or `rush_required`) requires a slack of only `1`–`2` units whereas relaxing `strict_board_budget_cap` requires a slack of `14,000` dollars, unweighted $L_1$ minimization naturally highlights the smallest-magnitude repair (`rush_required`) needed to restore feasibility.
77
+ ### Z3 (`m.check({ solver: "z3" })`)
78
+
79
+ Z3 supports continuous variables (`m.continuous()`, such as `budget` above) and decimal coefficients. It returns all four conflicting rules while excluding `minimum_one_employee`, regardless of numeric scale.
80
+
81
+ ### Pumpkin (`m.check({ solver: "pumpkin" })`)
82
+
83
+ Pumpkin is bundled with `@ohtaman/washi` (no extra import required) and needs neither `z3-solver` nor browser `COOP` / `COEP` headers. If every variable is a bounded integer or boolean (for example, changing `budget` to `m.integer()`), Pumpkin also extracts a scale-invariant Unsat Core.
84
+
85
+ ### HiGHS (`m.check({ solver: "highs" })`)
86
+
87
+ Rather than an Unsat Core, HiGHS returns an **Elastic Repair Set** — constraints whose total slack (relaxation) needed to restore feasibility is minimized. It populates `conflicts` and leaves `unsatCore` as `undefined`, whereas Z3 and Pumpkin populate both. Because relaxing `rush_required` takes `1` unit while relaxing the budget cap takes `$14,000`, HiGHS flags `rush_required`.