@ohtaman/washi 0.7.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.
- package/README.ja.md +60 -23
- package/README.md +59 -22
- package/README.zh-CN.md +62 -25
- package/THIRD_PARTY_LICENSES.md +34 -1
- package/dist/browser/solvers/glpk.js +289 -238
- package/dist/browser/solvers/glpk.min.js +1 -1
- package/dist/browser/solvers/highs-__vite-browser-external-Dn-83hnF.js +7 -0
- package/dist/browser/solvers/highs-browser-runtime-0Bgq5ksG.js +2021 -0
- package/dist/browser/{loader-DewlSho8.js → solvers/highs-loader-BLY3wzDH.js} +190 -149
- package/dist/browser/solvers/highs-worker.js +54 -0
- package/dist/browser/solvers/highs.js +1414 -0
- package/dist/browser/solvers/highs.wasm +0 -0
- package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
- package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
- package/dist/browser/solvers/pumpkin-worker.js +45 -0
- package/dist/browser/solvers/pumpkin.js +1777 -0
- package/dist/browser/solvers/pumpkin.wasm +0 -0
- package/dist/browser/solvers/pumpkin.wasm.LICENSE +21 -0
- package/dist/browser/solvers/z3.js +1600 -1335
- package/dist/browser/solvers/z3.min.js +2 -2
- package/dist/browser/washi.js +3313 -1699
- package/dist/browser/washi.min.js +5 -3
- package/dist/lib/solvers/__vite-browser-external-oLchLuMx.js +7 -0
- package/dist/lib/solvers/glpk.js +174 -132
- package/dist/lib/solvers/highs-browser-runtime.js +2413 -0
- package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
- package/dist/lib/solvers/highs-runtime.js +16 -0
- package/dist/lib/solvers/highs-worker.js +54 -0
- package/dist/lib/solvers/highs.js +410 -0
- package/dist/lib/solvers/highs.wasm +0 -0
- package/dist/lib/{loader-BZUQNvh4.js → solvers/loader-CDpPXN_F.js} +138 -116
- package/dist/lib/solvers/loader-Ow74Fa1B.js +311 -0
- package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
- package/dist/lib/solvers/pumpkin-assets.js +1 -0
- package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
- package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
- package/dist/lib/solvers/pumpkin-worker.js +45 -0
- package/dist/lib/solvers/pumpkin.js +868 -0
- package/dist/lib/solvers/pumpkin.wasm +0 -0
- package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
- package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
- package/dist/lib/solvers/rolldown-runtime-DtPi1Y-2.js +13 -0
- package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
- package/dist/lib/solvers/z3.js +489 -307
- package/dist/lib/washi.js +3905 -1410
- package/dist/types/decomposition/benders.d.ts.map +1 -1
- package/dist/types/index.d.ts +4 -5
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/modeler/boolean-expr.d.ts +137 -29
- package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
- package/dist/types/modeler/constraint.d.ts +40 -4
- package/dist/types/modeler/constraint.d.ts.map +1 -1
- package/dist/types/modeler/expression.d.ts +129 -2
- package/dist/types/modeler/expression.d.ts.map +1 -1
- package/dist/types/modeler/index.d.ts +4 -6
- package/dist/types/modeler/index.d.ts.map +1 -1
- package/dist/types/modeler/linearizer.d.ts +11 -2
- package/dist/types/modeler/linearizer.d.ts.map +1 -1
- package/dist/types/modeler/lp-writer.d.ts.map +1 -1
- package/dist/types/modeler/model.d.ts +86 -126
- package/dist/types/modeler/model.d.ts.map +1 -1
- package/dist/types/modeler/parser.d.ts.map +1 -1
- package/dist/types/modeler/quad-expr.d.ts +8 -2
- package/dist/types/modeler/quad-expr.d.ts.map +1 -1
- package/dist/types/modeler/solution-validator.d.ts +12 -12
- package/dist/types/modeler/solution-validator.d.ts.map +1 -1
- package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
- package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
- package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
- package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
- package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
- package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
- package/dist/types/modeler/solvers/index.d.ts +2 -1
- package/dist/types/modeler/solvers/index.d.ts.map +1 -1
- package/dist/types/modeler/solvers/mock.d.ts +2 -3
- package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
- package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
- package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
- package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
- package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
- package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
- package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
- package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
- package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
- package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
- package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
- package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
- package/dist/types/modeler/solvers/types.d.ts +7 -9
- package/dist/types/modeler/solvers/types.d.ts.map +1 -1
- package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
- package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
- package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
- package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
- package/dist/types/modeler/types.d.ts +12 -15
- package/dist/types/modeler/types.d.ts.map +1 -1
- package/dist/types/modeler/validation.d.ts +26 -2
- package/dist/types/modeler/validation.d.ts.map +1 -1
- package/dist/types/modeler/variable.d.ts +9 -5
- package/dist/types/modeler/variable.d.ts.map +1 -1
- package/docs/examples/diet-sensitivity.md +33 -14
- package/docs/examples/ecommerce-coupons.md +17 -9
- package/docs/examples/index.md +36 -27
- package/docs/examples/knapsack.md +11 -5
- package/docs/examples/portfolio-qp.md +21 -8
- package/docs/examples/production.md +10 -5
- package/docs/examples/project-scheduling.md +119 -0
- package/docs/examples/shift-scheduling.md +29 -18
- package/docs/examples/smt-security.md +27 -11
- package/docs/examples/transportation.md +23 -13
- package/docs/examples/traveling-salesperson.md +34 -22
- package/docs/examples/unsat-core.md +27 -14
- package/docs/examples/vehicle-routing.md +74 -28
- package/docs/getting-started/ai-agents.md +190 -82
- package/docs/getting-started/coding-agents.md +177 -0
- package/docs/getting-started/cross-origin.md +27 -14
- package/docs/getting-started/index.md +49 -43
- package/docs/getting-started/runtimes.md +94 -40
- package/docs/guide/constraint-programming.md +171 -0
- package/docs/guide/constraints.md +115 -33
- package/docs/guide/decomposition.md +118 -88
- package/docs/guide/expressions.md +106 -43
- package/docs/guide/formulation-tips.md +47 -28
- package/docs/guide/objectives.md +102 -75
- package/docs/guide/unsat-core.md +62 -50
- package/docs/guide/variables.md +81 -35
- package/docs/solvers/custom-solver.md +163 -122
- package/docs/solvers/glpk.md +58 -17
- package/docs/solvers/highs.md +124 -57
- package/docs/solvers/index.md +33 -20
- package/docs/solvers/pumpkin.md +171 -0
- package/docs/solvers/z3.md +63 -25
- package/llms-full.txt +2232 -932
- package/llms.txt +144 -91
- package/package.json +55 -19
- package/skills/washi/SKILL.md +107 -34
- package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
- package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
- package/dist/browser/highs-worker.js +0 -39
- package/dist/browser/highs.wasm +0 -0
- package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
- package/dist/lib/highs-browser-runtime.js +0 -2185
- package/dist/lib/highs-runtime.js +0 -2
- package/dist/lib/highs-worker.js +0 -39
- package/dist/lib/highs.wasm +0 -0
- package/dist/lib/registry-D7TZ3Wh_.js +0 -1034
- package/docs/ja/getting-started/ai-agents.md +0 -280
- package/docs/zh/getting-started/ai-agents.md +0 -280
- /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
- /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
- /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
- /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
|
@@ -1,22 +1,23 @@
|
|
|
1
1
|
# AI Coding Agent Quick-Reference Guide
|
|
2
2
|
|
|
3
|
-
> **Scope Note**: This document is the **
|
|
4
|
-
>
|
|
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
|
|
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**:
|
|
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
|
|
20
|
+
### Node.js, Bun, & Bundlers (Vite, Webpack, Next.js)
|
|
20
21
|
|
|
21
22
|
```ts
|
|
22
23
|
import {
|
|
@@ -24,6 +25,14 @@ import {
|
|
|
24
25
|
expr,
|
|
25
26
|
sum,
|
|
26
27
|
dot,
|
|
28
|
+
abs,
|
|
29
|
+
max,
|
|
30
|
+
min,
|
|
31
|
+
at,
|
|
32
|
+
distinct,
|
|
33
|
+
disjoint,
|
|
34
|
+
cumulative,
|
|
35
|
+
allowed,
|
|
27
36
|
maximize,
|
|
28
37
|
minimize,
|
|
29
38
|
and,
|
|
@@ -31,9 +40,13 @@ import {
|
|
|
31
40
|
not,
|
|
32
41
|
implies,
|
|
33
42
|
xor,
|
|
34
|
-
setHighsWasmUrl,
|
|
35
43
|
} from "@ohtaman/washi";
|
|
36
44
|
|
|
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
|
+
|
|
37
50
|
// Optional solver plugins (require installing peer dependencies first):
|
|
38
51
|
// npm install z3-solver
|
|
39
52
|
import "@ohtaman/washi/solvers/z3";
|
|
@@ -43,31 +56,47 @@ import "@ohtaman/washi/solvers/glpk";
|
|
|
43
56
|
|
|
44
57
|
### Browser ESM & Classic Script Tags
|
|
45
58
|
|
|
46
|
-
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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`) |
|
|
54
68
|
|
|
55
69
|
### WebAssembly Asset & Runtime Rules
|
|
56
70
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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.
|
|
71
100
|
|
|
72
101
|
---
|
|
73
102
|
|
|
@@ -85,7 +114,7 @@ const x = m.continuous("x", { lb: 0, ub: 100 });
|
|
|
85
114
|
const y = m.continuous("y", { lb: 0, ub: 100 });
|
|
86
115
|
const n = m.integer("n", { lb: 0, ub: 10 });
|
|
87
116
|
const b = m.binary("b");
|
|
88
|
-
const flag = m.bool("flag"); // Propositional boolean (
|
|
117
|
+
const flag = m.bool("flag"); // Propositional boolean (auto 0-1 MIP on HiGHS/GLPK, native CP/SMT on Pumpkin/Z3)
|
|
89
118
|
|
|
90
119
|
// Indexed variable containers:
|
|
91
120
|
// - Numeric dimension -> Array
|
|
@@ -96,28 +125,40 @@ const byItem = m.integer(["desk", "chair"] as const, { lb: 0 }); // Record<"desk
|
|
|
96
125
|
const mixed = m.binary(["A", "B"] as const, 3); // Record<"A" | "B", Var[]>
|
|
97
126
|
```
|
|
98
127
|
|
|
99
|
-
- **
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
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.
|
|
131
|
+
|
|
132
|
+
### Step 2: Build Expressions (`expr`, `sum`, `dot`, `max`, `min`, `abs`, `at`)
|
|
133
|
+
|
|
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). |
|
|
117
158
|
|
|
118
159
|
### Step 3: Register Objective & Constraints on the Model
|
|
119
160
|
|
|
120
|
-
Constructing an `expr` or `.le()`
|
|
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:
|
|
121
162
|
|
|
122
163
|
```ts
|
|
123
164
|
// Set objective using maximize() or minimize()
|
|
@@ -126,28 +167,35 @@ m.objective(maximize(expr`30 * ${x} + 50 * ${n}`));
|
|
|
126
167
|
// Register constraints on the model (returns the registered Constraint / BoolExpr or array)
|
|
127
168
|
const limit = m.constraint(expr`${x} + 2 * ${n} <= 40`, "resource_limit");
|
|
128
169
|
|
|
129
|
-
// Indicator constraint (
|
|
170
|
+
// Indicator constraint (b === 1 => x <= 50; Big-M on MIP, native on Pumpkin/Z3)
|
|
130
171
|
m.indicator(b, expr`${x} <= 50`, { activeValue: 1, name: "cap_when_b" });
|
|
131
172
|
```
|
|
132
173
|
|
|
133
|
-
### Step 4: Execute (`solve` or `check`) & Verify (`
|
|
174
|
+
### Step 4: Execute (`solve` or `check`) & Verify (`verify`)
|
|
175
|
+
|
|
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).
|
|
134
189
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
- Call `m.validateSolution()` after solving to independently verify variable finiteness, variable bounds (`lb`/`ub`), integer/binary/boolean domains, linear constraint residuals, and logical constraints (`SolutionValidationReport`: `{ valid, complete, maxViolation, violations, ... }`). Note that `validateSolution()` checks primal feasibility of variables and constraints; it does not recompute or compare `m.objectiveValue`.
|
|
139
|
-
- **Satisfiability & Conflict Diagnosis (`await m.check(options?)`)**:
|
|
140
|
-
- 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"`.
|
|
141
|
-
- For models containing linear arithmetic constraints or logical constraints (`BoolVar`, `and`, `or`, `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).
|
|
142
|
-
- Exact SMT unsatisfiable-core extraction (`result.unsatCore` and `result.conflicts`) is provided when using an SMT-capable solver (`{ solver: "z3" }`). Because Z3 asserts 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).
|
|
143
|
-
- **No concurrent mutation during async solve/check**:
|
|
144
|
-
- 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.
|
|
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.
|
|
145
193
|
|
|
146
194
|
---
|
|
147
195
|
|
|
148
196
|
## 3. Executable Examples
|
|
149
197
|
|
|
150
|
-
### Example A: Mixed-Integer Linear Programming (MIP) with Indexed Containers & Solution
|
|
198
|
+
### Example A: Mixed-Integer Linear Programming (MIP) with Indexed Containers & Solution Verification
|
|
151
199
|
|
|
152
200
|
```ts
|
|
153
201
|
import { Model, expr, dot, sum, maximize } from "@ohtaman/washi";
|
|
@@ -171,23 +219,25 @@ export async function runMipExample() {
|
|
|
171
219
|
});
|
|
172
220
|
|
|
173
221
|
const status = await m.solve();
|
|
174
|
-
const report = m.
|
|
175
|
-
const values = m.
|
|
222
|
+
const report = m.hasPrimalSolution ? m.verify() : null;
|
|
223
|
+
const values = m.hasPrimalSolution
|
|
224
|
+
? { desk: qty.desk.value, chair: qty.chair.value }
|
|
225
|
+
: null;
|
|
176
226
|
|
|
177
227
|
return {
|
|
178
228
|
status,
|
|
179
229
|
objectiveValue: m.objectiveValue,
|
|
180
230
|
values,
|
|
181
|
-
setup: setup.value,
|
|
182
|
-
valid: report
|
|
183
|
-
maxViolation: report
|
|
231
|
+
setup: m.hasPrimalSolution ? setup.value : null,
|
|
232
|
+
valid: report?.valid ?? false,
|
|
233
|
+
maxViolation: report?.maxViolation ?? null,
|
|
184
234
|
};
|
|
185
235
|
}
|
|
186
236
|
```
|
|
187
237
|
|
|
188
238
|
### Example B: Convex Quadratic Programming (QP)
|
|
189
239
|
|
|
190
|
-
|
|
240
|
+
Products of two variables (`${x} * ${y}`) and squares (`${x}^2`) are supported in `expr` for quadratic objectives:
|
|
191
241
|
|
|
192
242
|
```ts
|
|
193
243
|
import { Model, expr, minimize } from "@ohtaman/washi";
|
|
@@ -202,14 +252,14 @@ export async function runQpExample() {
|
|
|
202
252
|
m.constraint(expr`${x} + ${y} >= 4`, "budget");
|
|
203
253
|
|
|
204
254
|
const status = await m.solve();
|
|
205
|
-
const report = m.
|
|
255
|
+
const report = m.hasPrimalSolution ? m.verify() : null;
|
|
206
256
|
|
|
207
257
|
return {
|
|
208
258
|
status,
|
|
209
259
|
objectiveValue: m.objectiveValue,
|
|
210
|
-
x: x.value,
|
|
211
|
-
y: y.value,
|
|
212
|
-
valid: report
|
|
260
|
+
x: m.hasPrimalSolution ? x.value : null,
|
|
261
|
+
y: m.hasPrimalSolution ? y.value : null,
|
|
262
|
+
valid: report?.valid ?? false,
|
|
213
263
|
};
|
|
214
264
|
}
|
|
215
265
|
```
|
|
@@ -233,6 +283,63 @@ export async function runZ3Example() {
|
|
|
233
283
|
return {
|
|
234
284
|
status: unsatResult.status,
|
|
235
285
|
conflicts: unsatResult.conflicts,
|
|
286
|
+
unsatCore: unsatResult.unsatCore,
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
### Example D: Pumpkin CP Scheduling & Discrete Unsat Core
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
import { Model, expr, disjoint, distinct, implies, minimize } from "@ohtaman/washi";
|
|
295
|
+
|
|
296
|
+
export async function runPumpkinExample() {
|
|
297
|
+
// Part 1: Bounded-integer CP scheduling with native global propagators
|
|
298
|
+
const cpModel = new Model("WorkshopSchedule", { solver: "pumpkin" });
|
|
299
|
+
const start = cpModel.integer(["cut", "weld", "paint"] as const, { lb: 0, ub: 20, prefix: "start" });
|
|
300
|
+
const bench = cpModel.integer(["cut", "weld", "paint"] as const, { lb: 1, ub: 3, prefix: "bench" });
|
|
301
|
+
|
|
302
|
+
cpModel.constraint(
|
|
303
|
+
disjoint([
|
|
304
|
+
{ start: start.cut, duration: 4 },
|
|
305
|
+
{ start: start.weld, duration: 3 },
|
|
306
|
+
{ start: start.paint, duration: 2 },
|
|
307
|
+
]),
|
|
308
|
+
"single_line"
|
|
309
|
+
);
|
|
310
|
+
cpModel.constraint(expr`${start.cut} + 4 <= ${start.weld}`, "cut_before_weld");
|
|
311
|
+
cpModel.constraint(expr`${start.weld} + 3 <= ${start.paint}`, "weld_before_paint");
|
|
312
|
+
cpModel.constraint(distinct(bench), "unique_benches");
|
|
313
|
+
cpModel.objective(minimize(expr`${start.paint} + 2`));
|
|
314
|
+
|
|
315
|
+
const status = await cpModel.solve();
|
|
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
|
|
325
|
+
const unsatModel = new Model("DiscreteConflict", { solver: "pumpkin" });
|
|
326
|
+
const vip = unsatModel.bool("vip");
|
|
327
|
+
const discount = unsatModel.integer("discount", { lb: 0, ub: 50 });
|
|
328
|
+
|
|
329
|
+
unsatModel.constraint(vip, "customer_is_vip");
|
|
330
|
+
unsatModel.constraint(implies(vip, expr`${discount} >= 20`), "vip_min_discount");
|
|
331
|
+
unsatModel.constraint(expr`${discount} <= 10`, "campaign_cap");
|
|
332
|
+
|
|
333
|
+
const unsatResult = await unsatModel.check();
|
|
334
|
+
return {
|
|
335
|
+
status,
|
|
336
|
+
makespan: cpModel.objectiveValue,
|
|
337
|
+
starts,
|
|
338
|
+
benches,
|
|
339
|
+
valid: report?.valid ?? false,
|
|
340
|
+
unsatStatus: unsatResult.status,
|
|
341
|
+
conflicts: unsatResult.conflicts,
|
|
342
|
+
unsatCore: unsatResult.unsatCore,
|
|
236
343
|
};
|
|
237
344
|
}
|
|
238
345
|
```
|
|
@@ -255,28 +362,29 @@ export function verifyNegativePatterns() {
|
|
|
255
362
|
// WRONG: m.objective(maximize(expr`${x} <= 10` as any)); -> throws Error
|
|
256
363
|
// WRONG: expr`${x} + 1`.add(expr`${y} <= 5` as any); -> throws Error
|
|
257
364
|
|
|
258
|
-
// 2. DO NOT pass
|
|
365
|
+
// 2. DO NOT pass a bare arithmetic expression without a comparison operator (<=, >=, ==, etc.) to m.constraint():
|
|
259
366
|
// WRONG: m.constraint(expr`${x} + ${y}` as any); -> throws Error
|
|
260
367
|
|
|
261
|
-
// 3. DO NOT use quadratic terms
|
|
368
|
+
// 3. DO NOT use quadratic terms in constraints:
|
|
262
369
|
// WRONG: expr`${x}^2 <= 10`; -> throws Error ("Quadratic constraints are not supported")
|
|
263
370
|
|
|
264
|
-
// 4. DO NOT use retired aliases
|
|
371
|
+
// 4. DO NOT use retired aliases:
|
|
265
372
|
// - Use `expr` instead of retired `c` template tag
|
|
266
373
|
// - Use `m.constraint(...)` instead of `m.constrain(...)` or `m.add(...)`
|
|
267
|
-
// - Use `m.objective(maximize(...))` / `m.objective(minimize(...))` instead of `m.maximize(...)` / `m.minimize(...)` / `m.setObjective(...)`
|
|
374
|
+
// - Use `m.objective(maximize(...))` / `m.objective(minimize(...))` / `m.objective()` instead of `m.maximize(...)` / `m.minimize(...)` / `m.setObjective(...)` / `m.objectiveExpr`
|
|
268
375
|
// - Use `await m.solve()` instead of `await m.optimize()`
|
|
376
|
+
// - Use `m.verify()` instead of `m.validateSolution()` (and rely on automatic integrity validation in `solve()` / `check()` / `toLpString()` instead of `m.validateIntegrity()`)
|
|
377
|
+
// - Use `m.column(...)` instead of `m.addColumn(...)`
|
|
269
378
|
// - Use `.le()`, `.ge()`, `.eq()` instead of `.lessThanOrEqual()`, `.greaterThanOrEqual()`, `.equalTo()`
|
|
270
|
-
// - Use `.value`
|
|
271
|
-
// - Use `m.variables` / `m.constraints` instead of `m.vars` / `m.constrs`
|
|
379
|
+
// - Use `.value` instead of `m.getValues(...)` or `expr.getValue()`
|
|
380
|
+
// - Use `m.variables` / `m.constraints` (`ReadonlyMap` with `.get()` / `.size`) instead of `m.vars` / `m.constrs` / `m.boolVars` / `m.logicalConstraints` / `m.numVars` / `m.numConstrs` / `get*ByName()`
|
|
381
|
+
// - Use `relativeGap` / `absoluteGap` instead of `relGap` / `mipGap` / `absGap`
|
|
272
382
|
return { m, x, y, maximize };
|
|
273
383
|
}
|
|
274
384
|
```
|
|
275
385
|
|
|
276
386
|
### Practical OR Modeling Guardrails
|
|
277
387
|
|
|
278
|
-
- **Prefer inequalities
|
|
279
|
-
- **
|
|
280
|
-
- **
|
|
281
|
-
|
|
282
|
-
|
|
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.
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# Coding with AI Agents
|
|
2
|
+
|
|
3
|
+
This guide explains how to configure AI coding agents to build, verify, and package `@ohtaman/washi` optimization and constraint models. It covers tools such as Claude Code, Cursor, Codex, Antigravity, Gemini CLI, and Windsurf.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Setup
|
|
8
|
+
|
|
9
|
+
Setting up WaSHI with a coding agent has two parts. First, install the runtime library in your project. Second, connect your agent to WaSHI's API reference and verification workflow.
|
|
10
|
+
|
|
11
|
+
### Install the Runtime Library
|
|
12
|
+
|
|
13
|
+
Installing `@ohtaman/washi` bundles **HiGHS** for linear, mixed-integer, and convex quadratic programming (`LP`/`MIP`/`QP`), along with **Pumpkin** for Constraint Programming (`CP`), with zero external dependencies:
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @ohtaman/washi
|
|
17
|
+
|
|
18
|
+
# Optional dependencies for Z3 (SMT / continuous logic) or GLPK:
|
|
19
|
+
# npm install z3-solver
|
|
20
|
+
# npm install glpk.js
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### Connect Your Coding Agent
|
|
24
|
+
|
|
25
|
+
Choose the integration method that matches your tool:
|
|
26
|
+
|
|
27
|
+
| Method | Best For | Setup |
|
|
28
|
+
| --- | --- | --- |
|
|
29
|
+
| **Agent Skill** *(Recommended)* | Claude Code, Cursor, Codex, Antigravity, Gemini CLI | Run `npx skills add ohtaman/washi` |
|
|
30
|
+
| **IDE `@Docs` Index** | Cursor, Windsurf | Add `https://washi.ohtaman.dev/llms.txt` or `https://washi.ohtaman.dev/llms-full.txt` |
|
|
31
|
+
| **Context7 MCP** | MCP-enabled agents | Reference library ID `/ohtaman/washi` |
|
|
32
|
+
|
|
33
|
+
Installing the Agent Skill places `SKILL.md` into your agent's skills directory. It teaches your agent solver selection, `expr` modeling, and debugging with `m.toLpString()`, `m.verify()`, and `m.check()`.
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## 2. Your First End-to-End Run
|
|
38
|
+
|
|
39
|
+
Copy and paste the starter prompt below into your coding agent inside a Node.js / TypeScript project where `@ohtaman/washi` is installed:
|
|
40
|
+
|
|
41
|
+
```text
|
|
42
|
+
Using @ohtaman/washi, write and run a TypeScript script that schedules 8 internal tech-talk sessions across 2 rooms (Room A, Room B) and 4 time slots.
|
|
43
|
+
Input data: create a sample array of talks with speaker, topic ("infra", "frontend", "data", "security"), and unavailable slots.
|
|
44
|
+
Requirements:
|
|
45
|
+
1. Assign every talk to exactly one room and one time slot, with at most one talk per room-slot.
|
|
46
|
+
2. Respect speaker unavailability and prevent any speaker from giving two talks in the same time slot.
|
|
47
|
+
3. Minimize the number of parallel talks sharing the same topic in the same time slot.
|
|
48
|
+
4. Give every constraint an explicit descriptive name, solve with bundled HiGHS, check m.hasPrimalSolution, and assert m.verify().valid === true before printing the timetable.
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
When you run this prompt, the agent executes three steps locally:
|
|
52
|
+
|
|
53
|
+
1. **Formulates the model**: Declares 0-1 binary variables with `m.binary()`, linear expressions with `` expr`...` `` and `sum()`, named constraints, and a minimization objective.
|
|
54
|
+
2. **Solves in Node.js via WebAssembly**: Runs the script (for example via `npx tsx schedule.ts`) using the bundled HiGHS WebAssembly binary. No Python runtime or native solver installation is needed.
|
|
55
|
+
3. **Independently verifies the solution**: Checks `m.hasPrimalSolution` and calls `m.verify()`. This confirms variable bounds, integrality, and constraint satisfaction before printing results.
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## 3. Problem Classes & Ready-to-Use Prompts
|
|
60
|
+
|
|
61
|
+
Match your task to the problem class and solver below, then customize the corresponding prompt template:
|
|
62
|
+
|
|
63
|
+
| Problem Class | Recommended Solver | Key Primitives |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| Assignment, timetabling, 0-1 selection (`MILP` / `0-1 MIP`) | Bundled **HiGHS** | `m.binary()`, `sum()`, `dot()` |
|
|
66
|
+
| Task scheduling with shared resources (`CP`) | Bundled **Pumpkin** | `disjoint()`, `cumulative()`, `distinct()` |
|
|
67
|
+
| Target balancing & variance minimization (Convex `QP`) | Bundled **HiGHS** | `m.continuous()`, `` expr`...^2` `` |
|
|
68
|
+
| Rule conflict diagnosis (`unsatCore`) | Bundled **Pumpkin** or optional **Z3** | `m.check()` |
|
|
69
|
+
|
|
70
|
+
### Reviewer Assignment & Load Balancing (MILP — Bundled HiGHS)
|
|
71
|
+
|
|
72
|
+
```text
|
|
73
|
+
Using @ohtaman/washi (bundled HiGHS), assign 24 pull-request / RFC submissions to 6 engineers so each submission gets 2 distinct reviewers.
|
|
74
|
+
Rules:
|
|
75
|
+
- Authors cannot review their own submissions, and reviewers must match at least one required domain tag on the submission.
|
|
76
|
+
- Respect each engineer's maximum review cap, and minimize the maximum workload assigned to any single engineer (min-max load balancing).
|
|
77
|
+
- Name every constraint, run the script, and verify m.hasPrimalSolution and m.verify().valid === true.
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Budget & Project Portfolio Selection (0-1 MIP — Bundled HiGHS)
|
|
81
|
+
|
|
82
|
+
```text
|
|
83
|
+
Using @ohtaman/washi (bundled HiGHS), select a subset of candidate engineering projects from a JSON list to maximize total expected annual savings.
|
|
84
|
+
Each project has cost, backend_engineers, frontend_engineers, and savings.
|
|
85
|
+
Rules:
|
|
86
|
+
- Stay within a total quarterly budget of 120 and headcount caps of 14 backend and 10 frontend engineers.
|
|
87
|
+
- Dependency: if "billing_v2" is selected, "auth_token_service" must also be selected.
|
|
88
|
+
- Mutual exclusion: select at most one of "legacy_search_tuning" and "vector_search_migration".
|
|
89
|
+
- Give every constraint a clear name and confirm m.verify().valid === true.
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Task Scheduling with Precedence & Shared Resources (CP — Bundled Pumpkin)
|
|
93
|
+
|
|
94
|
+
```text
|
|
95
|
+
Using @ohtaman/washi and its bundled CP solver ({ solver: "pumpkin" }), schedule 10 release-pipeline tasks with integer start times (lb: 0, ub: 120) and fixed durations to minimize total makespan.
|
|
96
|
+
Rules:
|
|
97
|
+
- Enforce finish-to-start precedence edges between dependent tasks.
|
|
98
|
+
- Tasks using the staging benchmark cluster cannot overlap (use disjoint).
|
|
99
|
+
- All running tasks share at most 4 concurrent CI runners at any time (use cumulative).
|
|
100
|
+
- Solve with { solver: "pumpkin" }, verify m.hasPrimalSolution and m.verify().valid === true, and print start/end times for each task.
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Target-Balancing & Variance Minimization (Convex QP — Bundled HiGHS)
|
|
104
|
+
|
|
105
|
+
Built-in HiGHS solves convex quadratic objectives over continuous variables (`m.continuous()`):
|
|
106
|
+
|
|
107
|
+
```text
|
|
108
|
+
Using @ohtaman/washi (bundled HiGHS), allocate a continuous total budget of 1.0 across 5 regional compute pools using m.continuous() variables (lb: 0.05, ub: 0.50).
|
|
109
|
+
Target weights are [0.30, 0.25, 0.20, 0.15, 0.10], plus a policy cap that regions 0 and 1 combined cannot exceed 0.48.
|
|
110
|
+
Minimize the sum of squared deviations expr`sum((${w} - ${target})^2)` subject to sum(w) == 1.0 and the regional cap, then verify m.verify().valid === true.
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Rule & Configuration Conflict Diagnosis (Infeasibility / Unsat Core)
|
|
114
|
+
|
|
115
|
+
```text
|
|
116
|
+
Using @ohtaman/washi, check whether a set of deployment and feature-flag rules over bounded integer and boolean variables is satisfiable via await m.check({ solver: "pumpkin" }).
|
|
117
|
+
Include a sample test case with contradictory named rules, print res.status and res.unsatCore (or res.conflicts), and show which named rules conflict with each other.
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
> [!NOTE]
|
|
121
|
+
> `await m.check()` works with default **HiGHS**, which reports conflicting constraint names in `res.conflicts`.
|
|
122
|
+
>
|
|
123
|
+
> To extract an exact unsatisfiable core (`res.unsatCore`), choose the solver by variable domain:
|
|
124
|
+
> - **Bounded integers and booleans**: Pass `{ solver: "pumpkin" }` (bundled with `@ohtaman/washi`; no extra import or browser `COOP`/`COEP` headers required).
|
|
125
|
+
> - **Continuous or fractional arithmetic**: Install `z3-solver` and import `@ohtaman/washi/solvers/z3`.
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## 4. Packaging & Deployment Prompts (Browser, Desktop & Mobile)
|
|
130
|
+
|
|
131
|
+
Once a CLI script produces verified results, ask your agent to package the same model as a local HTML tool or an offline app.
|
|
132
|
+
|
|
133
|
+
### Zero-Server Single-File `.html` Tool (Double-Click via `file://`)
|
|
134
|
+
|
|
135
|
+
```text
|
|
136
|
+
Package this @ohtaman/washi optimization model into a standalone .html file with inline HTML, CSS, and JavaScript so team members can open it directly by double-clicking (file://).
|
|
137
|
+
- Load WaSHI from https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/washi.min.js (global window.Washi).
|
|
138
|
+
- Provide a textarea / CSV file input, a "Solve" button, a table displaying the optimal assignment, and a conflict report using await m.check() if status is "Infeasible".
|
|
139
|
+
- Verify every feasible solve with m.verify().
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
**`file://` runtime notes**: Loading `washi.min.js` from an HTTPS CDN runs directly on `file://`—under `window.origin === "null"`, WaSHI automatically falls back to main-thread execution. Self-hosted `.wasm` files require `http://` or `https://`, and browser Z3 requires Cross-Origin Isolation; see [Runtime Environments](./runtimes.md) and [Cross-Origin Isolation](./cross-origin.md).
|
|
143
|
+
|
|
144
|
+
### Offline Desktop & Mobile Apps (Vite + Tauri / Capacitor / PWA)
|
|
145
|
+
|
|
146
|
+
```text
|
|
147
|
+
Wrap this Vite + TypeScript @ohtaman/washi application as an offline desktop/mobile app using bundled HiGHS (or { solver: "pumpkin" }) with zero backend server and zero native solver compilation.
|
|
148
|
+
- Keep all solver execution client-side via @ohtaman/washi.
|
|
149
|
+
- Configure Content Security Policy to allow WebAssembly compilation ('wasm-unsafe-eval' in script-src) and Web Workers (worker-src 'self' blob:).
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
**WebView notes**: Standard Vite builds bundle your solver `.wasm` assets for offline execution in Tauri, Capacitor, and PWAs. Allow `'wasm-unsafe-eval'` in `script-src` (plus `worker-src 'self' blob:` for Web Workers); see [Runtime Environments](./runtimes.md) for a `tauri.conf.json` example.
|
|
153
|
+
|
|
154
|
+
---
|
|
155
|
+
|
|
156
|
+
## 5. Iterating & Debugging with Your Agent
|
|
157
|
+
|
|
158
|
+
### Name Every Constraint and Verify Every Solve
|
|
159
|
+
|
|
160
|
+
Ask your agent to pass a descriptive name to `m.constraint(c, "rule_name")` and `m.indicator(b, c, { name: "rule_name" })`, then assert `m.verify().valid === true`. Unnamed constraints default to auto-generated IDs (`c_1`, `c_2` for linear constraints; `lc_1`, `lc_2` for logical constraints), which makes conflict reports harder to read.
|
|
161
|
+
|
|
162
|
+
### Diagnose `"Infeasible"` Models with `m.check()`
|
|
163
|
+
|
|
164
|
+
When adding a new rule makes `m.solve()` return `"Infeasible"`, send a follow-up prompt like this:
|
|
165
|
+
|
|
166
|
+
```text
|
|
167
|
+
Adding the new constraints made m.solve() return "Infeasible".
|
|
168
|
+
Run await m.check() (or await m.check({ solver: "pumpkin" }) for bounded integer/boolean models), print res.conflicts / res.unsatCore, explain in plain terms which named rules and variable bounds contradict each other, and propose which non-rigid constraints should be converted into soft constraints with non-negative slack penalty variables.
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Inspect `m.toLpString()` and Variable Bounds Before Production
|
|
172
|
+
|
|
173
|
+
Have your agent print `m.toLpString()` on a small test fixture before shipping. Confirm three items:
|
|
174
|
+
|
|
175
|
+
- **Finite bounds (`lb` / `ub`)**: Variables inside `m.indicator()` require finite bounds whenever `M` is omitted.
|
|
176
|
+
- **Objective sense**: Check that `Maximize` vs. `Minimize` matches your business goal.
|
|
177
|
+
- **Constraint operators**: Verify that every `<=`, `>=`, and `=` operator and direction matches your intent.
|