@ohtaman/washi 0.7.0 → 0.8.0

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 (139) hide show
  1. package/README.ja.md +58 -19
  2. package/README.md +58 -19
  3. package/README.zh-CN.md +58 -19
  4. package/THIRD_PARTY_LICENSES.md +34 -1
  5. package/dist/browser/__vite-browser-external-rTVKos2U.js +7 -0
  6. package/dist/browser/browser-runtime-AG5QFtKf.js +2021 -0
  7. package/dist/browser/highs-worker.js +26 -11
  8. package/dist/browser/highs.wasm +0 -0
  9. package/dist/browser/{loader-DewlSho8.js → loader-i3FnqMes.js} +183 -149
  10. package/dist/browser/solvers/glpk.js +289 -238
  11. package/dist/browser/solvers/glpk.min.js +1 -1
  12. package/dist/browser/solvers/pumpkin-_washi-pumpkin-node-runtime-CEKUDK6d.js +9 -0
  13. package/dist/browser/solvers/pumpkin-loader-CvdaKxf4.js +320 -0
  14. package/dist/browser/solvers/pumpkin-worker.js +45 -0
  15. package/dist/browser/solvers/pumpkin.js +1777 -0
  16. package/dist/browser/solvers/pumpkin.min.js +1 -0
  17. package/dist/browser/solvers/pumpkin.wasm +0 -0
  18. package/dist/browser/solvers/pumpkin.wasm.LICENSE +21 -0
  19. package/dist/browser/solvers/z3.js +1600 -1335
  20. package/dist/browser/solvers/z3.min.js +2 -2
  21. package/dist/browser/washi.js +3374 -1377
  22. package/dist/browser/washi.min.js +5 -3
  23. package/dist/lib/__vite-browser-external-oLchLuMx.js +7 -0
  24. package/dist/lib/highs-browser-runtime.js +1846 -1618
  25. package/dist/lib/highs-runtime.js +16 -2
  26. package/dist/lib/highs-worker.js +26 -11
  27. package/dist/lib/highs.wasm +0 -0
  28. package/dist/lib/{loader-BZUQNvh4.js → loader-CDpPXN_F.js} +138 -116
  29. package/dist/lib/registry-dx7x4e5c.js +1694 -0
  30. package/dist/lib/rolldown-runtime-DtPi1Y-2.js +13 -0
  31. package/dist/lib/solvers/glpk.js +161 -121
  32. package/dist/lib/solvers/pumpkin-assets.js +1 -0
  33. package/dist/lib/solvers/pumpkin-loader-Ow74Fa1B.js +311 -0
  34. package/dist/lib/solvers/pumpkin-node-runtime.js +15 -0
  35. package/dist/lib/solvers/pumpkin-worker-factory.js +1 -0
  36. package/dist/lib/solvers/pumpkin-worker.js +45 -0
  37. package/dist/lib/solvers/pumpkin.js +1767 -0
  38. package/dist/lib/solvers/pumpkin.wasm +0 -0
  39. package/dist/lib/solvers/pumpkin.wasm.LICENSE +21 -0
  40. package/dist/lib/solvers/z3.js +486 -306
  41. package/dist/lib/washi.js +2563 -1154
  42. package/dist/types/decomposition/benders.d.ts.map +1 -1
  43. package/dist/types/index.d.ts +3 -3
  44. package/dist/types/index.d.ts.map +1 -1
  45. package/dist/types/modeler/boolean-expr.d.ts +137 -29
  46. package/dist/types/modeler/boolean-expr.d.ts.map +1 -1
  47. package/dist/types/modeler/constraint.d.ts +40 -4
  48. package/dist/types/modeler/constraint.d.ts.map +1 -1
  49. package/dist/types/modeler/expression.d.ts +129 -2
  50. package/dist/types/modeler/expression.d.ts.map +1 -1
  51. package/dist/types/modeler/index.d.ts +4 -5
  52. package/dist/types/modeler/index.d.ts.map +1 -1
  53. package/dist/types/modeler/linearizer.d.ts +11 -2
  54. package/dist/types/modeler/linearizer.d.ts.map +1 -1
  55. package/dist/types/modeler/lp-writer.d.ts.map +1 -1
  56. package/dist/types/modeler/model.d.ts +85 -124
  57. package/dist/types/modeler/model.d.ts.map +1 -1
  58. package/dist/types/modeler/parser.d.ts.map +1 -1
  59. package/dist/types/modeler/quad-expr.d.ts +8 -2
  60. package/dist/types/modeler/quad-expr.d.ts.map +1 -1
  61. package/dist/types/modeler/solution-validator.d.ts +12 -12
  62. package/dist/types/modeler/solution-validator.d.ts.map +1 -1
  63. package/dist/types/modeler/solvers/glpk/loader.d.ts +4 -0
  64. package/dist/types/modeler/solvers/glpk/loader.d.ts.map +1 -1
  65. package/dist/types/modeler/solvers/glpk/solver.d.ts +2 -2
  66. package/dist/types/modeler/solvers/glpk/solver.d.ts.map +1 -1
  67. package/dist/types/modeler/solvers/highs/driver.d.ts.map +1 -1
  68. package/dist/types/modeler/solvers/highs/loader.d.ts +8 -6
  69. package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
  70. package/dist/types/modeler/solvers/highs/solver.d.ts.map +1 -1
  71. package/dist/types/modeler/solvers/highs/worker-client.d.ts +16 -0
  72. package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
  73. package/dist/types/modeler/solvers/mock.d.ts +2 -3
  74. package/dist/types/modeler/solvers/mock.d.ts.map +1 -1
  75. package/dist/types/modeler/solvers/pumpkin/assets.d.ts +2 -0
  76. package/dist/types/modeler/solvers/pumpkin/assets.d.ts.map +1 -0
  77. package/dist/types/modeler/solvers/pumpkin/index.d.ts +6 -0
  78. package/dist/types/modeler/solvers/pumpkin/index.d.ts.map +1 -0
  79. package/dist/types/modeler/solvers/pumpkin/loader.d.ts +40 -0
  80. package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -0
  81. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts +3 -0
  82. package/dist/types/modeler/solvers/pumpkin/node-runtime.d.ts.map +1 -0
  83. package/dist/types/modeler/solvers/pumpkin/solver.d.ts +23 -0
  84. package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -0
  85. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts +74 -0
  86. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -0
  87. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts +3 -0
  88. package/dist/types/modeler/solvers/pumpkin/worker-factory.d.ts.map +1 -0
  89. package/dist/types/modeler/solvers/pumpkin/worker.d.ts +7 -0
  90. package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -0
  91. package/dist/types/modeler/solvers/pumpkin.d.ts +2 -0
  92. package/dist/types/modeler/solvers/pumpkin.d.ts.map +1 -0
  93. package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
  94. package/dist/types/modeler/solvers/types.d.ts +7 -9
  95. package/dist/types/modeler/solvers/types.d.ts.map +1 -1
  96. package/dist/types/modeler/solvers/z3/loader.d.ts +4 -0
  97. package/dist/types/modeler/solvers/z3/loader.d.ts.map +1 -1
  98. package/dist/types/modeler/solvers/z3/solver.d.ts +2 -15
  99. package/dist/types/modeler/solvers/z3/solver.d.ts.map +1 -1
  100. package/dist/types/modeler/types.d.ts +12 -15
  101. package/dist/types/modeler/types.d.ts.map +1 -1
  102. package/dist/types/modeler/validation.d.ts +26 -2
  103. package/dist/types/modeler/validation.d.ts.map +1 -1
  104. package/dist/types/modeler/variable.d.ts +9 -5
  105. package/dist/types/modeler/variable.d.ts.map +1 -1
  106. package/docs/examples/index.md +6 -1
  107. package/docs/examples/project-scheduling.md +106 -0
  108. package/docs/examples/shift-scheduling.md +3 -0
  109. package/docs/examples/smt-security.md +1 -0
  110. package/docs/examples/traveling-salesperson.md +1 -1
  111. package/docs/examples/unsat-core.md +3 -2
  112. package/docs/getting-started/ai-agents.md +94 -25
  113. package/docs/getting-started/coding-agents.md +158 -0
  114. package/docs/getting-started/cross-origin.md +2 -2
  115. package/docs/getting-started/index.md +40 -41
  116. package/docs/getting-started/runtimes.md +42 -18
  117. package/docs/guide/constraint-programming.md +141 -0
  118. package/docs/guide/constraints.md +64 -14
  119. package/docs/guide/decomposition.md +59 -59
  120. package/docs/guide/expressions.md +42 -10
  121. package/docs/guide/formulation-tips.md +6 -6
  122. package/docs/guide/objectives.md +65 -62
  123. package/docs/guide/unsat-core.md +36 -27
  124. package/docs/guide/variables.md +30 -17
  125. package/docs/solvers/custom-solver.md +18 -13
  126. package/docs/solvers/highs.md +18 -23
  127. package/docs/solvers/index.md +12 -6
  128. package/docs/solvers/pumpkin.md +163 -0
  129. package/docs/solvers/z3.md +2 -2
  130. package/llms-full.txt +944 -314
  131. package/llms.txt +43 -22
  132. package/package.json +38 -11
  133. package/skills/washi/SKILL.md +79 -27
  134. package/dist/browser/_washi-node-only-BvRk9kiK.js +0 -0
  135. package/dist/browser/browser-runtime-TLCY0hkc.js +0 -1793
  136. package/dist/lib/_washi-node-only-BvRk9kiK.js +0 -0
  137. package/dist/lib/registry-D7TZ3Wh_.js +0 -1034
  138. package/docs/ja/getting-started/ai-agents.md +0 -280
  139. package/docs/zh/getting-started/ai-agents.md +0 -280
@@ -1,7 +1,7 @@
1
1
  # AI Coding Agent Quick-Reference Guide
2
2
 
3
3
  > **Scope Note**: This document is the **consumer modeling quick-reference** for AI coding agents and developers building optimization or satisfiability models with `@ohtaman/washi`.
4
- > - **Portable Agent Skill (`SKILL.md`)**: For an actionable end-to-end modeling, `toLpString()` inspection, `validateSolution()` verification, and Z3 `unsatCore` conflict-diagnosis workflow skill (compatible with Claude Code, Antigravity, Cursor, Codex, and other `SKILL.md`-aware agents), use [`skills/washi/SKILL.md`](https://github.com/ohtaman/washi/blob/main/skills/washi/SKILL.md) (also shipped in the npm package at `node_modules/@ohtaman/washi/skills/washi/SKILL.md`):
4
+ > - **Portable Agent Skill (`SKILL.md`)**: For an actionable end-to-end modeling, `toLpString()` inspection, `verify()` verification, and Pumpkin / Z3 `unsatCore` conflict-diagnosis workflow skill (compatible with Claude Code, Antigravity, Cursor, Codex, and other `SKILL.md`-aware agents), use [`skills/washi/SKILL.md`](https://github.com/ohtaman/washi/blob/main/skills/washi/SKILL.md) (also shipped in the npm package at `node_modules/@ohtaman/washi/skills/washi/SKILL.md`):
5
5
  > ```bash
6
6
  > # Install directly via the skills CLI (skills.sh / vercel-labs/skills)
7
7
  > npx skills add ohtaman/washi
@@ -24,6 +24,14 @@ import {
24
24
  expr,
25
25
  sum,
26
26
  dot,
27
+ abs,
28
+ max,
29
+ min,
30
+ at,
31
+ distinct,
32
+ disjoint,
33
+ cumulative,
34
+ allowed,
27
35
  maximize,
28
36
  minimize,
29
37
  and,
@@ -34,6 +42,8 @@ import {
34
42
  setHighsWasmUrl,
35
43
  } from "@ohtaman/washi";
36
44
 
45
+ // Bundled CP/LCG solver plugin (zero external dependencies; registers "pumpkin"):
46
+ import { setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
37
47
  // Optional solver plugins (require installing peer dependencies first):
38
48
  // npm install z3-solver
39
49
  import "@ohtaman/washi/solvers/z3";
@@ -45,10 +55,12 @@ import "@ohtaman/washi/solvers/glpk";
45
55
 
46
56
  - **Browser ESM**:
47
57
  - Core (HiGHS built-in): `import { Model, expr, maximize } from "./washi/washi.js";`
58
+ - Pumpkin plugin: `import "./washi/solvers/pumpkin.js";`
48
59
  - GLPK plugin: `import "./washi/solvers/glpk.js";`
49
60
  - Z3 plugin: `import "./washi/solvers/z3.js";`
50
61
  - **Classic `<script>` / CodePen (IIFE)**:
51
62
  - Core: `<script src="./washi/washi.min.js"></script>` (exposes global `Washi`)
63
+ - Pumpkin plugin: `<script src="./washi/solvers/pumpkin.min.js"></script>` (registers `"pumpkin"`, exposes `WashiPumpkin`)
52
64
  - GLPK plugin: `<script src="./washi/solvers/glpk.min.js"></script>` (registers `"glpk"`, exposes `WashiGLPK`)
53
65
  - Z3 plugin: `<script src="./washi/solvers/z3.min.js"></script>` (registers `"z3"`, exposes `WashiZ3`)
54
66
 
@@ -57,7 +69,8 @@ import "@ohtaman/washi/solvers/glpk";
57
69
  1. **Bundled WASM by default (no implicit CDN fallback)**:
58
70
  - In Node.js and modern bundlers, WebAssembly assets resolve relative to the module automatically.
59
71
  - In browser deployments, deploy the full `dist/browser/` directory (JS, Worker, and `.wasm` files) together. If a local WASM URL is missing or returns an HTML SPA fallback, initialization fails immediately and reports the attempted URL—it **never** silently switches to a public CDN.
60
- - In browser runtimes, to load `highs.wasm` from a custom location, call `setHighsWasmUrl("https://.../highs.wasm")` or pass `await m.solve({ wasmUrl: "https://.../highs.wasm" })` (ignored in Node.js, which always loads WaSHI's bundled local `highs.wasm` runtime).
72
+ - In browser runtimes, to load `highs.wasm` or `pumpkin.wasm` from a custom location, call `setHighsWasmUrl("https://.../highs.wasm")` (or `await m.solve({ wasmUrl: "https://.../highs.wasm" })`) for HiGHS, or `setPumpkinWasmUrl("https://.../pumpkin.wasm")` (or `await m.solve({ solver: "pumpkin", wasmUrl: "https://.../pumpkin.wasm" })`) for Pumpkin (ignored in Node.js for HiGHS; for Pumpkin in Node.js, bundled local `pumpkin.wasm` is used by default unless overridden with a `file://` URL).
73
+ - **Pumpkin runs without `COOP`/`COEP`**: Unlike Z3, Pumpkin (`@ohtaman/washi/solvers/pumpkin`) uses single-threaded WASM inside a regular Web Worker and does **not** require `SharedArrayBuffer` or Cross-Origin Isolation headers (`COOP`/`COEP`). It requires bounded finite integer/binary variables (`lb`, `ub` in `[-(2^30 - 1), 2^30 - 1]`) and integer linear coefficients/RHS, and supports `initialValue` warm starts across `solve()` and `check()` (no `Continuous`, `QuadExpr`, or `relax: true`).
61
74
  2. **Z3 requires a Secure Context, Cross-Origin Isolation, and CORS in browsers**:
62
75
  - Z3 WebAssembly uses `SharedArrayBuffer` multithreading. Browser pages running Z3 must run in a secure context (`window.isSecureContext === true`, i.e., HTTPS or `localhost`) and be cross-origin isolated (`window.crossOriginIsolated === true`) by serving:
63
76
  - `Cross-Origin-Opener-Policy: same-origin` (on the document)
@@ -66,8 +79,8 @@ import "@ohtaman/washi/solvers/glpk";
66
79
  - Importing `@ohtaman/washi` never auto-injects a Service Worker. When a secure context or cross-origin isolation is absent in a browser, Z3 rejects immediately with a descriptive error.
67
80
  3. **Web Workers & Cancellation (`AbortSignal`)**:
68
81
  - Pre-solve cancellation (`signal.aborted` before execution starts) is supported across all solvers.
69
- - In browsers where `Worker` is available on a non-opaque effective origin (`window.origin !== "null"`), HiGHS runs in a dedicated Web Worker by default (`useWorker: true`). On opaque effective origins (`window.origin === "null"`, such as `file:` URLs or `sandbox="allow-scripts"` `<iframe>` embeds without `allow-same-origin`), HiGHS defaults to main-thread execution (`useWorker: false`). Passing `{ signal }` to `m.solve({ signal })` preemptively terminates an in-flight Worker solve (or cancels queued Worker requests).
70
- - On main-thread HiGHS (`useWorker: false` or in Node.js), cooperative mid-solve cancellation is supported when `abort()` is triggered synchronously inside an `onProgress` callback at a solver interrupt checkpoint; arbitrary asynchronous aborts from outside cannot preempt a blocked synchronous WASM thread until a callback checkpoint or completion. Single-threaded WASM solvers without interrupt hooks (GLPK, Z3) check `signal` before execution starts.
82
+ - In browsers where `Worker` is available on a non-opaque effective origin (`window.origin !== "null"`), both **HiGHS** and **Pumpkin** run in dedicated Web Workers by default (`useWorker: true`). On opaque effective origins (`window.origin === "null"`, such as `file:` URLs or `sandbox="allow-scripts"` `<iframe>` embeds without `allow-same-origin`), both default to main-thread execution (`useWorker: false`). Passing `{ signal }` to `m.solve({ signal })` or `m.check({ signal })` preemptively terminates an in-flight Worker run (or cancels queued Worker requests).
83
+ - On main-thread HiGHS (`useWorker: false` or in Node.js), cooperative mid-solve cancellation is supported when `abort()` is triggered synchronously inside an `onProgress` callback at a solver interrupt checkpoint; arbitrary asynchronous aborts from outside cannot preempt a blocked synchronous WASM thread until a callback checkpoint or completion. Main-thread / Node.js Pumpkin checks `should_abort` checkpoints across branching and termination hooks. Single-threaded WASM solvers without interrupt hooks (GLPK, Z3) check `signal` before execution starts.
71
84
 
72
85
  ---
73
86
 
@@ -85,7 +98,7 @@ const x = m.continuous("x", { lb: 0, ub: 100 });
85
98
  const y = m.continuous("y", { lb: 0, ub: 100 });
86
99
  const n = m.integer("n", { lb: 0, ub: 10 });
87
100
  const b = m.binary("b");
88
- const flag = m.bool("flag"); // Propositional boolean (for Z3 / logical constraints)
101
+ const flag = m.bool("flag"); // Propositional boolean (auto 0-1 MIP on HiGHS/GLPK, native LCG/SMT on Pumpkin/Z3)
89
102
 
90
103
  // Indexed variable containers:
91
104
  // - Numeric dimension -> Array
@@ -99,25 +112,27 @@ const mixed = m.binary(["A", "B"] as const, 3); // Record<"A" | "B", Var[]>
99
112
  - **Optional Primal Initial Values (`initialValue?: number`)**:
100
113
  - Numeric variable constructors (`m.continuous`, `m.integer`, `m.binary`, and `new Var`) and the mutable `v.initialValue` property accept an optional finite primal hint (validated with tolerance `1e-6` against bounds `[lb, ub]` and integer/binary domains), kept distinct from the solved `v.value`.
101
114
  - A start may be complete or partial (e.g., transferred by stable variable names when rebuilding a MIP model). Supplying `initialValue` is a hint only—it does **not** fix the variable, add a hard constraint, or guarantee solver acceptance or a runtime speedup.
102
- - Supported by **HiGHS** (`supportsWarmStart: true`); solvers without warm-start support (**GLPK**, **Z3**) throw an error if any variable has `initialValue !== undefined`.
115
+ - Supported by **HiGHS** and **Pumpkin** (`supportsWarmStart: true`); solvers without warm-start support (**GLPK**, **Z3**) throw an error if any variable has `initialValue !== undefined`.
103
116
 
104
- ### Step 2: Build Expressions (`expr`, `sum`, `dot`)
117
+ ### Step 2: Build Expressions (`expr`, `sum`, `dot`, `max`, `min`, `abs`, `at`)
105
118
 
106
119
  - **Unified `expr` template tag**:
107
120
  - Linear expression (`LinExpr`): `` expr`30 * ${x} + 50 * ${n} - 10` ``, `` expr`dot(${profit}, ${byItem}) - 20 * ${b}` ``, `` expr`sum((${price} - ${cost}) * ${byItem})` ``
121
+ - Piecewise-linear & element primitives (`max`, `min`, `abs`, `at`, usable inside `expr` or standalone): `` expr`max(${vec}) + sum(abs(${vec} - ${target}))` ``, `` expr`max(abs(${pred} - ${actual}))` ``, `` expr`at(${costs}, ${idx})` `` (0-based integer `idx`, automatically enforcing $0 \le \text{idx} < \text{costs.length}$). On HiGHS/GLPK, convex directions (`minimize` or `<=` on `max`/`abs`, `maximize` or `>=` on `min`) lower to pure continuous LP epigraphs with zero binary variables, while non-convex/equality contexts use exact bounded MIP formulations (finite bounds required); Pumpkin lowers natively (`maximum`/`minimum`/`absolute`/`element`) and Z3 uses native `If` (ITE).
108
122
  - Quadratic expression (`QuadExpr`): `` expr`${x}^2 + 2 * ${x} * ${y} + ${y}^2` ``, `` expr`sum((${vec} - ${target})^2)` `` (supported for convex QP objectives on purely continuous models using `m.continuous`; built-in HiGHS does not support MIQP models containing integer, binary, or boolean variables).
109
- - Linear constraint (`Constraint`): `` expr`${x} + 2 * ${n} <= 40` ``, `` expr`sum(${byItem}) <= 100` `` (supports `<=`, `>=`, `==`, and `=`).
123
+ - Constraint (`Constraint`): `` expr`${x} + 2 * ${n} <= 40` ``, `` expr`sum(${byItem}) <= 100` `` (supports `<=`, `>=`, `==`, `=`, plus discrete integer-only `<`, `>`, `!=`).
110
124
  - **Aggregations & Element-Wise Container Arithmetic**:
111
- - `sum(containerOrItems, mapper?)` (usable inside `` expr`sum(...)` `` or standalone `sum(...)`) sums a 1D/2D `Array`, `Iterable`, or plain `Record` of `Var` / `LinExpr` / `number` (without needing `Object.values(record)`), or maps over items/counts via `sum(items, (item, i) => ...)`. Inside `` expr`sum(...)` ``, element-wise container arithmetic (`+`, `-`, `*`, `/`, `^2`) is also supported.
125
+ - `sum(containerOrItems, mapper?)` (usable inside `` expr`sum(...)` `` or standalone `sum(...)`) sums a 1D/2D `Array`, `Iterable`, or plain `Record` of `Var` / `LinExpr` / `number` (without needing `Object.values(record)`), or maps over items/counts via `sum(items, (item, i) => ...)`. Inside `` expr`sum(...)` ``, element-wise container arithmetic (`+`, `-`, `*`, `/`, `^2`) and `abs(...)` mapping are also supported.
112
126
  - `dot(a, b)` (usable inside `` expr`dot(${a}, ${b})` `` or standalone `dot(a, b)`) computes the inner product of matching 1D arrays, 2D arrays (`number[][]` / `Var[][]`, computing the Frobenius inner product $\sum_{i,j} A_{i,j} B_{i,j}$), plain records (`Record<string, ...>`), or mixed Array/Record containers in either operand order.
113
127
  - **Fluent methods**:
114
128
  - Arithmetic (on `LinExpr` and `QuadExpr`; `Var` supports `.add()`, `.sub()`, `.mul()`, `.neg()`): `.add(other)`, `.sub(other)`, `.mul(other)`, `.div(scalar)`, `.neg()`
115
- - Comparisons (on `Var` and `LinExpr`): `.le(rhs, name?)`, `.ge(rhs, name?)`, `.eq(rhs, name?)`
116
- - Boolean logic (on `BoolVar`, `BoolExpr`, and `Constraint` for Z3): standalone `and(...)`, `or(...)`, `not(...)`, `implies(a, b)`, `xor(a, b)` and fluent `.and(...)`, `.or(...)`, `.not()`, `.implies(...)`, `.xor(...)`
129
+ - Comparisons (on `Var`, `LinExpr`, and `QuadExpr`): `.le(rhs, name?)`, `.ge(rhs, name?)`, `.eq(rhs, name?)`, plus discrete integer-only `.lt(rhs, name?)`, `.gt(rhs, name?)`, `.ne(rhs, name?)` (Continuous / fractional operands throw immediately)
130
+ - CP global constraints (`BoolExpr` predicates composable with logical operators): `distinct(...args)` (pairwise `!=` on HiGHS/GLPK, `all_different` via pairwise `binary_not_equals` on Pumpkin `0.5.0`, `ctx.Distinct` on Z3), `disjoint(tasks)` (`{ start, duration }`, native `disjunctive_strict` Vilím edge-finding on Pumpkin), `cumulative(tasks, capacity)` (`{ start, duration, demand }`, native `cumulative` time-table on Pumpkin; MIP time-indexed formulation enforces a horizon memory guard recommending `{ solver: "pumpkin" }`), and `allowed(vars, tuples)` (`table` / `negative_table` on Pumpkin)
131
+ - Boolean logic (on `BoolVar`, `BoolExpr`, and `Constraint`): standalone `and(...)`, `or(...)`, `not(...)`, `implies(a, b)`, `xor(a, b)` and fluent `.and(...)`, `.or(...)`, `.not()`, `.implies(...)`, `.xor(...)`—solved natively on Z3 and Pumpkin (bounded integers) and automatically linearized to 0-1 MIP on HiGHS/GLPK (negated comparison `Constraint`s in `implies` antecedents, `not`, or `xor` use exact $\pm 1$ shifts over integer-valued `Integer`/`Binary` expressions; `Continuous` or non-integer negated `Constraint`s throw on MIP solvers—use `{ solver: "z3" }`, or write ``or(expr`... >= ... + eps`, ...)`` / `m.bool()`)
117
132
 
118
133
  ### Step 3: Register Objective & Constraints on the Model
119
134
 
120
- Constructing an `expr` or `.le()` object does **not** attach it to the model until you pass it to `m.constraint(...)` or `m.objective(...)`:
135
+ Constructing an `expr` or `.le()` object does **not** attach it to the model until you pass it to `m.constraint(...)` or `m.objective(...)` (when `options.M` is omitted in `m.indicator()`, HiGHS/GLPK use tight derived Big-M and preserve `toLpString()`, while Pumpkin lowers natively via `implied_by` and Z3 via `ctx.Implies` unless the returned `Constraint` row is subsequently mutated):
121
136
 
122
137
  ```ts
123
138
  // Set objective using maximize() or minimize()
@@ -130,16 +145,16 @@ const limit = m.constraint(expr`${x} + 2 * ${n} <= 40`, "resource_limit");
130
145
  m.indicator(b, expr`${x} <= 50`, { activeValue: 1, name: "cap_when_b" });
131
146
  ```
132
147
 
133
- ### Step 4: Execute (`solve` or `check`) & Verify (`validateSolution`)
148
+ ### Step 4: Execute (`solve` or `check`) & Verify (`verify`)
134
149
 
135
150
  - **Optimization (`await m.solve(options?)`)**:
136
151
  - Returns `SolverStatus` (`"Optimal"`, `"Feasible"`, `"Infeasible"`, `"Unbounded"`, `"TimeLimit"`, `"IterationLimit"`, `"Error"`, `"Unknown"`, `"NotSolved"`, `"Sat"`, or `"Unsat"`). Built-in optimization solvers return the optimization statuses (`"Optimal"`, `"Feasible"`, `"Infeasible"`, `"Unbounded"`, `"TimeLimit"`, `"IterationLimit"`, `"Error"`, `"Unknown"`, `"NotSolved"`), where a time-, iteration-, or solution-limited run (or an interrupted solve) that found a valid primal incumbent returns `"Feasible"`; `"Sat"` and `"Unsat"` are included in `SolverStatus` for satisfiability/custom solver adapters (such as `MockSolver`).
137
- - Read values via `x.value`, `expr`...`.value`, `m.getValues(x)`, `m.getValues(container)`, `m.objectiveValue`, `constr.dual`, `constr.slack`, and `x.reducedCost`.
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`.
152
+ - Read values via `x.value`, `expr`...`.value`, `m.values`, `m.objectiveValue`, `constr.dual`, `constr.slack`, and `x.reducedCost`, and inspect registered entities via `m.variables` (`ReadonlyMap<string, Var | BoolVar>`) and `m.constraints` (`ReadonlyMap<string, Constraint | LogicalConstraint>`).
153
+ - Call `m.verify()` after solving to independently verify variable finiteness, variable bounds (`lb`/`ub`), integer/binary/boolean domains, linear constraint residuals, and logical constraints (`VerificationReport`: `{ valid, complete, maxViolation, violations, ... }`). Note that `verify()` checks primal feasibility of variables and constraints; it does not recompute or compare `m.objectiveValue`.
139
154
  - **Satisfiability & Conflict Diagnosis (`await m.check(options?)`)**:
140
155
  - Returns `CheckResult` (`{ status: "Sat" | "Unsat" | "Unknown", values: Record<string, number | boolean>, conflicts?: readonly string[], unsatCore?: readonly string[], runTime?: number }`), where `conflicts` is populated when the model is proven `"Unsat"`.
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).
156
+ - For models containing linear arithmetic constraints or logical constraints (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`), `m.check()` works with any solver (including the default HiGHS and GLPK via single-solve elastic slack relaxation, automatically linearizing logical constraints into 0-1 MIP formulation) and diagnoses conflicting constraints as `conflicts` (leaving `unsatCore: undefined` for semantic rigor).
157
+ - Exact unsatisfiable-core extraction (`result.unsatCore` and `result.conflicts`) is provided when using `{ solver: "z3" }` or `{ solver: "pumpkin" }`. Use `"pumpkin"` (`@ohtaman/washi/solvers/pumpkin`) for bounded-integer/propositional models in environments without `COOP`/`COEP` headers, and use `"z3"` when `Continuous` variables or fractional arithmetic are involved. Because Z3 and Pumpkin assert variable bounds (`lb`/`ub`) and binary `{0, 1}` domains directly while tracking registered constraints, `unsatCore` reports a subset of registered constraint names that conflicts *together with the model's fixed variable bounds/domains* (and is not guaranteed minimal).
143
158
  - **No concurrent mutation during async solve/check**:
144
159
  - Mutating variables, constraints, or the objective while `await m.solve()` or `await m.check()` is pending invalidates the in-flight execution and rejects the stale promise.
145
160
 
@@ -171,8 +186,8 @@ export async function runMipExample() {
171
186
  });
172
187
 
173
188
  const status = await m.solve();
174
- const report = m.validateSolution();
175
- const values = m.getValues(qty);
189
+ const report = m.verify();
190
+ const values = { desk: qty.desk.value, chair: qty.chair.value };
176
191
 
177
192
  return {
178
193
  status,
@@ -202,7 +217,7 @@ export async function runQpExample() {
202
217
  m.constraint(expr`${x} + ${y} >= 4`, "budget");
203
218
 
204
219
  const status = await m.solve();
205
- const report = m.validateSolution();
220
+ const report = m.verify();
206
221
 
207
222
  return {
208
223
  status,
@@ -237,6 +252,57 @@ export async function runZ3Example() {
237
252
  }
238
253
  ```
239
254
 
255
+ ### Example D: Pumpkin CP Disjunctive Scheduling & Zero-COOP/COEP Unsat Core
256
+
257
+ ```ts
258
+ import { Model, expr, disjoint, distinct, implies, minimize } from "@ohtaman/washi";
259
+ import "@ohtaman/washi/solvers/pumpkin";
260
+
261
+ export async function runPumpkinExample() {
262
+ // Part 1: Bounded-integer CP scheduling with native global propagators
263
+ const cpModel = new Model("WorkshopSchedule", { solver: "pumpkin" });
264
+ const start = cpModel.integer(["cut", "weld", "paint"] as const, { lb: 0, ub: 20, prefix: "start" });
265
+ const bench = cpModel.integer(["cut", "weld", "paint"] as const, { lb: 1, ub: 3, prefix: "bench" });
266
+
267
+ cpModel.constraint(
268
+ disjoint([
269
+ { start: start.cut, duration: 4 },
270
+ { start: start.weld, duration: 3 },
271
+ { start: start.paint, duration: 2 },
272
+ ]),
273
+ "single_line"
274
+ );
275
+ cpModel.constraint(expr`${start.cut} + 4 <= ${start.weld}`, "cut_before_weld");
276
+ cpModel.constraint(expr`${start.weld} + 3 <= ${start.paint}`, "weld_before_paint");
277
+ cpModel.constraint(distinct(bench), "unique_benches");
278
+ cpModel.objective(minimize(expr`${start.paint} + 2`));
279
+
280
+ const status = await cpModel.solve();
281
+ const report = cpModel.verify();
282
+
283
+ // Part 2: Zero-COOP/COEP unsatCore diagnosis on bounded integers & booleans
284
+ const unsatModel = new Model("DiscreteConflict", { solver: "pumpkin" });
285
+ const vip = unsatModel.bool("vip");
286
+ const discount = unsatModel.integer("discount", { lb: 0, ub: 50 });
287
+
288
+ unsatModel.constraint(vip, "customer_is_vip");
289
+ unsatModel.constraint(implies(vip, expr`${discount} >= 20`), "vip_min_discount");
290
+ unsatModel.constraint(expr`${discount} <= 10`, "campaign_cap");
291
+
292
+ const unsatResult = await unsatModel.check();
293
+ return {
294
+ status,
295
+ makespan: cpModel.objectiveValue,
296
+ starts: { cut: start.cut.value, weld: start.weld.value, paint: start.paint.value },
297
+ benches: { cut: bench.cut.value, weld: bench.weld.value, paint: bench.paint.value },
298
+ valid: report.valid,
299
+ unsatStatus: unsatResult.status,
300
+ conflicts: unsatResult.conflicts,
301
+ unsatCore: unsatResult.unsatCore,
302
+ };
303
+ }
304
+ ```
305
+
240
306
  ---
241
307
 
242
308
  ## 4. Negative Examples & Common Pitfalls
@@ -261,14 +327,17 @@ export function verifyNegativePatterns() {
261
327
  // 3. DO NOT use quadratic terms inside linear constraints:
262
328
  // WRONG: expr`${x}^2 <= 10`; -> throws Error ("Quadratic constraints are not supported")
263
329
 
264
- // 4. DO NOT use retired aliases (removed in #59 / #81):
330
+ // 4. DO NOT use retired aliases (removed in #59 / #81 / #236 / #273):
265
331
  // - Use `expr` instead of retired `c` template tag
266
332
  // - 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(...)`
333
+ // - Use `m.objective(maximize(...))` / `m.objective(minimize(...))` / `m.objective()` instead of `m.maximize(...)` / `m.minimize(...)` / `m.setObjective(...)` / `m.objectiveExpr`
268
334
  // - Use `await m.solve()` instead of `await m.optimize()`
335
+ // - Use `m.verify()` instead of `m.validateSolution()` (and rely on automatic integrity validation in `solve()` / `check()` / `toLpString()` instead of `m.validateIntegrity()`)
336
+ // - Use `m.column(...)` instead of `m.addColumn(...)`
269
337
  // - Use `.le()`, `.ge()`, `.eq()` instead of `.lessThanOrEqual()`, `.greaterThanOrEqual()`, `.equalTo()`
270
- // - Use `.value` or `m.getValues(...)` instead of `expr.getValue()`
271
- // - Use `m.variables` / `m.constraints` instead of `m.vars` / `m.constrs`
338
+ // - Use `.value` instead of `m.getValues(...)` or `expr.getValue()`
339
+ // - 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()`
340
+ // - Use `relativeGap` / `absoluteGap` instead of `relGap` / `mipGap` / `absGap`
272
341
  return { m, x, y, maximize };
273
342
  }
274
343
  ```
@@ -276,7 +345,7 @@ export function verifyNegativePatterns() {
276
345
  ### Practical OR Modeling Guardrails
277
346
 
278
347
  - **Prefer inequalities (`>=` / `<=`) over exact equalities (`==`)** for demand coverage and resource limits when objective costs are positive; reserve `==` for physical conservation laws (e.g., flow balance, portfolio weights summing to `1`).
279
- - **Always provide finite `lb` and `ub` bounds** on variables referenced inside `m.indicator(...)` and omit `M` so WaSHI automatically derives the tightest valid Big-M instead of falling back to `1e6`.
348
+ - **Always provide finite `lb` and `ub` bounds** on variables referenced inside `m.indicator(...)` and omit `M` so WaSHI automatically derives the tightest valid Big-M (`m.indicator()` throws if required bounds are infinite and no explicit `M` is provided).
280
349
  - **Use soft constraints (elastic slack variables)** for non-rigid business targets (e.g., preferred staffing, safety stock, day-off requests) by adding a non-negative slack variable (`lb: 0`) with a tiered objective penalty, reserving hard constraints for physical or legal invariants.
281
350
 
282
351
 
@@ -0,0 +1,158 @@
1
+ # Coding with AI Agents
2
+
3
+ This guide shows how to configure AI coding agents (Claude Code, Cursor, Codex, Antigravity, Gemini CLI, Windsurf) to formulate, solve, verify, and package optimization and constraint models with `@ohtaman/washi`.
4
+
5
+ ---
6
+
7
+ ## 1. Setup
8
+
9
+ Setting up WaSHI with a coding agent has two separate parts: installing the runtime library in your project, and giving your agent WaSHI's current API and verification workflow.
10
+
11
+ ### Install the Runtime Library
12
+
13
+ Bundled **HiGHS** (LP / MIP / Convex QP) and **Pumpkin** (`@ohtaman/washi/solvers/pumpkin`, CP / LCG) require zero external dependencies:
14
+
15
+ ```bash
16
+ npm install @ohtaman/washi
17
+
18
+ # Optional peer dependencies if your model requires 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 setup method that matches your tool:
26
+
27
+ - **Agent Skill (Recommended — Claude Code, Cursor, Codex, Antigravity, Gemini CLI)**:
28
+ ```bash
29
+ npx skills add ohtaman/washi
30
+ ```
31
+ This installs `skills/washi/SKILL.md` (also included at `node_modules/@ohtaman/washi/skills/washi/SKILL.md`), which guides the agent through solver selection across HiGHS / Pumpkin / Z3 / GLPK, algebraic `expr` modeling, `m.toLpString()` formulation checks, `m.verify()` solution verification, and `m.check()` conflict diagnosis.
32
+ - **IDE Documentation Indexing (`@Docs` in Cursor, Windsurf, etc.)**:
33
+ - Documentation index: `https://washi.ohtaman.dev/llms.txt`
34
+ - Complete single-file API & example reference: `https://washi.ohtaman.dev/llms-full.txt`
35
+ - **Context7 MCP**:
36
+ - Reference library ID: `/ohtaman/washi`
37
+
38
+ ---
39
+
40
+ ## 2. Your First End-to-End Run
41
+
42
+ Copy and paste the starter prompt below into your coding agent inside a Node.js / TypeScript project where `@ohtaman/washi` is installed:
43
+
44
+ ```text
45
+ 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.
46
+ Input data: create a sample array of talks with speaker, topic ("infra", "frontend", "data", "security"), and unavailable slots.
47
+ Requirements:
48
+ 1. Assign every talk to exactly one room and one time slot, with at most one talk per room-slot.
49
+ 2. Respect speaker unavailability and prevent any speaker from giving two talks in the same time slot.
50
+ 3. Minimize the number of parallel talks sharing the same topic in the same time slot.
51
+ 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.
52
+ ```
53
+
54
+ When you run this prompt, the agent executes three steps locally:
55
+
56
+ 1. **Formulates the model**: Creates bounded binary variables (`m.binary`), linear expressions (`` expr`...` ``, `sum`), named constraints (`m.constraint(..., "name")`), and an objective (`m.objective(minimize(...))`).
57
+ 2. **Solves in Node.js via WebAssembly**: Executes the script (for example with `npx tsx schedule.ts`) using the bundled HiGHS WebAssembly binary—no Python runtime or native solver installation is needed.
58
+ 3. **Independently verifies the solution**: Checks `m.hasPrimalSolution` and calls `m.verify()` so variable bounds, integrality, and constraint residuals are verified before displaying the output.
59
+
60
+ ---
61
+
62
+ ## 3. Problem Classes & Ready-to-Use Prompts
63
+
64
+ Each prompt below targets a specific mathematical problem class supported by WaSHI. Adjust the input schema and rules to match your data.
65
+
66
+ ### Event Timetable & Reviewer Assignment (MILP — Bundled HiGHS)
67
+
68
+ ```text
69
+ Using @ohtaman/washi (bundled HiGHS), assign 24 pull-request / RFC submissions to 6 engineers so each submission gets 2 distinct reviewers.
70
+ Rules:
71
+ - Authors cannot review their own submissions, and reviewers must match at least one required domain tag on the submission.
72
+ - Respect each engineer's maximum review cap, and minimize the maximum workload assigned to any single engineer (min-max load balancing).
73
+ - Name every constraint, run the script, and verify m.hasPrimalSolution and m.verify().valid === true.
74
+ ```
75
+
76
+ ### Budget & Project Portfolio Selection (0-1 MIP — Bundled HiGHS)
77
+
78
+ ```text
79
+ Using @ohtaman/washi (bundled HiGHS), select a subset of candidate engineering projects from a JSON list to maximize total expected annual savings.
80
+ Each project has cost, backend_engineers, frontend_engineers, and savings.
81
+ Rules:
82
+ - Stay within a total quarterly budget of 120 and headcount caps of 14 backend and 10 frontend engineers.
83
+ - Dependency: if "billing_v2" is selected, "auth_token_service" must also be selected.
84
+ - Mutual exclusion: select at most one of "legacy_search_tuning" and "vector_search_migration".
85
+ - Give every constraint a clear name and confirm m.verify().valid === true.
86
+ ```
87
+
88
+ ### Task Scheduling with Precedence & Shared Resources (CP/LCG — Bundled Pumpkin)
89
+
90
+ ```text
91
+ Using @ohtaman/washi and its bundled CP solver (@ohtaman/washi/solvers/pumpkin), schedule 10 release-pipeline tasks with integer start times (lb: 0, ub: 120) and fixed durations to minimize total makespan.
92
+ Rules:
93
+ - Enforce finish-to-start precedence edges between dependent tasks.
94
+ - Tasks using the staging benchmark cluster cannot overlap (use disjoint).
95
+ - All running tasks share at most 4 concurrent CI runners at any time (use cumulative).
96
+ - Solve with { solver: "pumpkin" }, verify m.hasPrimalSolution and m.verify().valid === true, and print start/end times for each task.
97
+ ```
98
+
99
+ ### Target-Balancing & Variance Minimization (Convex QP — Bundled HiGHS)
100
+
101
+ Built-in HiGHS solves convex quadratic objectives over continuous variables (`m.continuous`):
102
+
103
+ ```text
104
+ 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).
105
+ 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.
106
+ 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.
107
+ ```
108
+
109
+ ### Rule & Configuration Conflict Diagnosis (Infeasibility / Unsat Core)
110
+
111
+ ```text
112
+ Using @ohtaman/washi and @ohtaman/washi/solvers/pumpkin, check whether a set of deployment and feature-flag rules over bounded integer and boolean variables is satisfiable via await m.check({ solver: "pumpkin" }).
113
+ 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.
114
+ ```
115
+
116
+ > [!NOTE]
117
+ > `await m.check()` works out of the box with default **HiGHS** (reporting conflicting constraint names in `res.conflicts` via elastic slack relaxation). Import bundled `@ohtaman/washi/solvers/pumpkin` when you want `res.unsatCore` on bounded integer/boolean models without `COOP`/`COEP` headers, or install `z3-solver` (`@ohtaman/washi/solvers/z3`) when continuous/fractional constraints require exact SMT `unsatCore` extraction.
118
+
119
+ ---
120
+
121
+ ## 4. Packaging & Deployment Prompts (Browser, Desktop & Mobile)
122
+
123
+ Once a CLI script produces verified results, you can ask your coding agent to package the same model into a local browser tool or an offline desktop/mobile application.
124
+
125
+ ### Zero-Server Single-File `.html` Tool (`file://` Double-Click)
126
+
127
+ ```text
128
+ Package this @ohtaman/washi optimization model into a single standalone .html file with inline HTML, CSS, and JavaScript so team members can open it directly via file:// by double-clicking.
129
+ - Load WaSHI from https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/washi.min.js (global window.Washi).
130
+ - 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".
131
+ - Verify every feasible solve with m.verify().
132
+ ```
133
+
134
+ - **Runtime notes for `file://`**:
135
+ - Opening the `.html` file directly via `file://` (no local HTTP server) works out of the box when loading `washi.min.js` (and `solvers/pumpkin.min.js` when using Pumpkin) from an HTTPS CDN, because WaSHI detects opaque origins (`window.origin === "null"`) and automatically runs HiGHS and Pumpkin on the main thread.
136
+ - Self-hosted local `.wasm` files (which browsers block on `file://` under `fetch()` CORS rules) and **Z3** (`SharedArrayBuffer` requiring `COOP`/`COEP` headers) require serving over `http://` or `https://`.
137
+
138
+ ### Offline Desktop & Mobile Apps (Vite + Tauri / Capacitor / PWA)
139
+
140
+ ```text
141
+ Wrap this Vite + TypeScript @ohtaman/washi application as an offline desktop/mobile app using bundled HiGHS (or @ohtaman/washi/solvers/pumpkin) with zero backend server and zero native C++ solver compilation.
142
+ - Keep all solver execution client-side via @ohtaman/washi.
143
+ - Configure Content Security Policy to allow WebAssembly compilation ('wasm-unsafe-eval' in script-src) and Web Workers (worker-src 'self' blob:).
144
+ ```
145
+
146
+ - **Runtime notes for WebViews**: Standard Vite builds bundle `highs.wasm` and `pumpkin.wasm` as static assets that run offline inside Tauri (`tauri://localhost` / `http://tauri.localhost`), Capacitor WebViews, and Service Worker PWAs. See [Runtime Environments](./runtimes.md) for `tauri.conf.json` CSP configuration (`'wasm-unsafe-eval'`).
147
+
148
+ ---
149
+
150
+ ## 5. Iterating & Debugging with Your Agent
151
+
152
+ - **Require named constraints and `m.verify()`**: Always ask your agent to pass a descriptive name as the second argument to `m.constraint(c, "rule_name")` (and `name` in `m.indicator(...)`) and assert `m.verify().valid === true`. Unnamed constraints (`c_0`, `c_1`) make infeasibility reports hard to interpret.
153
+ - **Diagnose `"Infeasible"` results with `m.check()`**: When adding new business rules causes `m.solve()` to return `"Infeasible"`, use a follow-up prompt like:
154
+ ```text
155
+ Adding the new constraints made m.solve() return "Infeasible".
156
+ 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.
157
+ ```
158
+ - **Inspect `m.toLpString()` and variable bounds before production**: Ask your agent to dump `m.toLpString()` on a small fixture and review variable `lb` / `ub` bounds (especially on variables referenced inside `m.indicator()`, which require finite bounds when `M` is omitted), objective sense (`Maximize` vs `Minimize`), and constraint signs (`<=` vs `>=`).
@@ -3,7 +3,7 @@
3
3
  When running the **Z3** solver inside a web browser, Cross-Origin Isolation HTTP headers are required so the browser enables `SharedArrayBuffer`.
4
4
 
5
5
  > [!TIP]
6
- > **Not needed for HiGHS, GLPK, or Node.js**: The built-in **HiGHS** solver and **GLPK** plugin run in standard browser contexts without Cross-Origin Isolation or `SharedArrayBuffer`. Running Z3 in **Node.js** also requires no HTTP headers. You only need this page when using `@ohtaman/washi/solvers/z3` in the browser.
6
+ > **Not needed for HiGHS, Pumpkin, GLPK, or Node.js**: Bundled **HiGHS** and **Pumpkin** (`@ohtaman/washi/solvers/pumpkin`), as well as the **GLPK** plugin, run in standard browser contexts without Cross-Origin Isolation or `SharedArrayBuffer` (including Pumpkin CP solving, propositional logic, and `unsatCore` conflict diagnosis). Running Z3 in **Node.js** also requires no HTTP headers. You only need this page when using `@ohtaman/washi/solvers/z3` in the browser.
7
7
 
8
8
  ---
9
9
 
@@ -99,7 +99,7 @@ app.use((req, res, next) => {
99
99
 
100
100
  Platforms like GitHub Pages do not allow customizing HTTP response headers directly. You can use **`coi-serviceworker`** to inject the isolation headers via a client-side Service Worker:
101
101
 
102
- 1. Place `coi-serviceworker.js` at your site root.
102
+ 1. Obtain `coi-serviceworker.js` from [`coi-serviceworker`](https://github.com/gzuidhof/coi-serviceworker) (GitHub / npm) or WaSHI's reference [`public/coi-serviceworker.js`](https://github.com/ohtaman/washi/blob/main/public/coi-serviceworker.js), and place it at your site root.
103
103
  2. Load it in your HTML `<head>`:
104
104
 
105
105
  ```html
@@ -1,35 +1,12 @@
1
1
  # Introduction & Installation
2
2
 
3
- **WaSHI** (WebAssembly-backed, Solver-independent, High-level modeling Interface) brings the algebraic modeling style of Python's **PuLP** to the TypeScript and JavaScript ecosystem. Write expressions naturally with tagged templates (`expr`) and solve mathematical optimization problems directly in **Node.js and the browser** using WebAssembly solvers (**HiGHS**, **Z3**, and **GLPK**).
4
-
5
- ```typescript
6
- import { Model, expr, maximize } from "@ohtaman/washi";
7
-
8
- const m = new Model("production");
9
-
10
- // 1. Define decision variables with realistic finite bounds (lb / ub)
11
- const desks = m.integer("desks", { lb: 0, ub: 100 });
12
- const chairs = m.integer("chairs", { lb: 0, ub: 100 });
13
-
14
- // 2. Set the objective function and constraints
15
- m.objective(maximize(expr`30 * ${desks} + 50 * ${chairs}`));
16
- m.constraint(expr`${desks} + 2 * ${chairs} <= 40`, "wood_capacity");
17
- m.constraint(expr`2 * ${desks} + ${chairs} <= 50`, "labor_capacity");
18
-
19
- // 3. Solve (built-in HiGHS WebAssembly) and validate the solution
20
- const status = await m.solve();
21
- if (m.hasPrimalSolution) {
22
- const report = m.validateSolution();
23
- console.log(status, report.valid); // "Optimal", true
24
- console.log(`Profit: ${m.objectiveValue} (desks=${desks.value}, chairs=${chairs.value})`); // 1100 (desks=20, chairs=10)
25
- }
26
- ```
3
+ **WaSHI** (WebAssembly-backed, Solver-independent, High-level modeling Interface) brings the algebraic modeling style of Python's **PuLP** to the TypeScript and JavaScript ecosystem. Write expressions naturally with tagged templates (`expr`) and solve mathematical optimization and constraint programming problems directly in **Node.js and the browser** using WebAssembly solvers (**HiGHS**, **Pumpkin**, **Z3**, and **GLPK**).
27
4
 
28
5
  ---
29
6
 
30
7
  ## 📦 Installation
31
8
 
32
- The default **HiGHS** solver (LP / MIP / Convex QP) is bundled and works out of the box:
9
+ Both the default **HiGHS** solver (LP / MIP / Convex QP) and the **Pumpkin** CP/LCG solver (`@ohtaman/washi/solvers/pumpkin`) are bundled with zero external dependencies and work out of the box:
33
10
 
34
11
  ::: code-group
35
12
 
@@ -51,37 +28,59 @@ bun add @ohtaman/washi
51
28
 
52
29
  :::
53
30
 
54
- Install optional peer dependencies only if you need **Z3** (SMT logic & Unsat Core diagnosis) or **GLPK**:
31
+ Install optional peer dependencies when you need **Z3** (SMT logic and Unsat Core conflict diagnosis) or **GLPK**:
55
32
 
56
33
  ```bash
57
34
  npm install z3-solver # For SMT logic and Unsat Core conflict diagnosis
58
35
  npm install glpk.js # For GLPK solver (GPL-3.0)
59
36
  ```
60
37
 
38
+ Using an AI coding agent? See [Coding with AI Agents](./coding-agents.md) for `npx skills add ohtaman/washi`, `llms.txt`, and ready-to-use prompt templates.
39
+
61
40
  ---
62
41
 
63
- ## 💡 Why TypeScript & WebAssembly?
42
+ ## 🚀 Quick Start
64
43
 
65
- - **Zero native setup across Node.js and the browser**: No platform-specific C/C++ builds or separate Python runtimes to manage. A single `npm install` runs the same modeling code across **Node.js APIs, CLIs, and scripts** as well as in the **browser**.
66
- - **Lightweight embedding with standard Web APIs & UIs**: Go beyond local analysis scripts by shipping **interactive Web tools, mini-games, or Chrome extensions** that anyone can open via a URL with zero backend hosting cost. You can wire mathematical optimization directly into drag-and-drop UIs or **standard browser capabilities**—such as screen/camera capture and speech recognition (Web Speech API)—with no network round-trips or external data transfer.
67
- - **End-to-end type safety from app data to model**: Prevent common indexing and dictionary-key mistakes with TypeScript's type system. Typed variable dictionaries (`Record<K, Var>`) and variable-reference interpolation (`` expr`30 * ${qty.desk} <= 40` ``) connect directly to your application schemas, preserving compile-time variable/key checks, IDE autocompletion, and symbol renaming.
68
- - **Strong synergy with AI development & LLM workflows**: Keeping your application and optimization model in a **single TypeScript codebase** lets you validate everything in one test runner—without crossing a Python service boundary—and deploy easily as static assets or a single service. That tight test-and-deploy loop fits AI-assisted coding naturally, while at runtime you can pair flexible LLM extraction with exact solver feasibility and conflict diagnosis (`unsatCore`) in the same runtime.
44
+ Here is a complete production-planning model illustrating the three steps of a typical WaSHI workflow:
69
45
 
70
- ---
46
+ ```typescript
47
+ import { Model, expr, maximize } from "@ohtaman/washi";
71
48
 
72
- ## 🔍 Core Workflow Essentials
49
+ const m = new Model("production");
50
+
51
+ // 1. Define decision variables with realistic finite bounds (lb / ub)
52
+ const desks = m.integer("desks", { lb: 0, ub: 100 });
53
+ const chairs = m.integer("chairs", { lb: 0, ub: 100 });
54
+
55
+ // 2. Set the objective function and constraints
56
+ m.objective(maximize(expr`30 * ${desks} + 50 * ${chairs}`));
57
+ m.constraint(expr`${desks} + 2 * ${chairs} <= 40`, "wood_capacity");
58
+ m.constraint(expr`2 * ${desks} + ${chairs} <= 50`, "labor_capacity");
73
59
 
74
- Three practical habits cover the essentials shown in the snippet above:
60
+ // 3. Solve (built-in HiGHS WebAssembly) and verify the solution
61
+ const status = await m.solve();
62
+ if (m.hasPrimalSolution) {
63
+ const report = m.verify();
64
+ console.log(status, report.valid); // "Optimal", true
65
+ console.log(`Profit: ${m.objectiveValue} (desks=${desks.value}, chairs=${chairs.value})`); // 1100 (desks=20, chairs=10)
66
+ }
67
+ ```
75
68
 
76
- 1. **Set realistic finite bounds (`lb`, `ub`)**: When defining variables with `m.continuous`, `m.integer`, or `m.binary`, finite bounds strengthen MIP presolve and enable automatic tight Big-M derivation for logical constraints.
77
- 2. **Formulate objectives and constraints with `expr`**: Use `` m.objective(maximize(expr`...`)) `` and `` m.constraint(expr`... <= ...`, "name") ``. Naming constraints lets you pinpoint conflicting rules immediately if a model becomes infeasible.
78
- 3. **Check `hasPrimalSolution` and call `validateSolution()`**: After `await m.solve()`, check `m.hasPrimalSolution` before reading `.value` on variables, and call `m.validateSolution()` to independently verify that bounds, integrality, and constraints hold within tolerance.
69
+ 1. **Define decision variables (`lb`, `ub`)**: Create variables with `m.continuous()`, `m.integer()`, or `m.binary()`, providing finite `lb` and `ub` bounds when known.
70
+ 2. **Describe the objective and constraints (`expr`)**: Formulate equations naturally with `` expr`...` ``, and pass constraint names to make infeasibility debugging straightforward.
71
+ 3. **Solve and verify (`solve`, `verify`)**: `await m.solve()` runs the bundled HiGHS WebAssembly solver. Check `m.hasPrimalSolution` before reading `.value`, and call `m.verify()` to independently verify that bounds, integrality, and constraints hold.
79
72
 
80
73
  ---
81
74
 
82
75
  ## 🧭 Next Steps
83
76
 
84
- - **[Modeling Guide](../guide/variables.md)**: Array/dictionary variables, aggregations (`sum`, `dot`), logical constraints, and Unsat Core diagnosis
85
- - **[Examples & API Finder](../examples/)**: 11 runnable optimization and SMT recipes—from shift scheduling and portfolio QP to vehicle routing
86
- - **[Solvers Overview](../solvers/)**: Compare built-in HiGHS with optional Z3 and GLPK adapters
87
- - **[Runtime Environments](./runtimes.md)**: Setup details for Node.js, Vite / Next.js bundlers, CDNs, and static hosting
77
+ ### Choose Your Workflow
78
+
79
+ - **Build with an AI Coding Agent**: [Coding with AI Agents](./coding-agents.md) — Setup with `npx skills add`, `llms.txt` / Context7, ready-to-use prompt examples across problem types and deployment targets, and conflict debugging
80
+ - **Write Models Directly in TypeScript**: [Modeling Guide](../guide/variables.md) — Array/dictionary variables, aggregations (`sum`, `dot`), logical constraints, and conflict diagnosis
81
+
82
+ ### Reference & Examples
83
+
84
+ - **[Examples & API Finder](../examples/)**: 12 runnable optimization and SMT recipes—from shift scheduling and portfolio QP to vehicle routing
85
+ - **[Solvers Overview](../solvers/)**: Compare bundled HiGHS and Pumpkin with optional Z3 and GLPK adapters
86
+ - **[Runtime Environments](./runtimes.md)**: Setup details for Node.js, Vite / Next.js bundlers, CDNs, standalone HTML, and desktop/mobile WebViews