chiasmus 0.1.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 (71) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +124 -0
  3. package/dist/formalize/engine.d.ts +47 -0
  4. package/dist/formalize/engine.d.ts.map +1 -0
  5. package/dist/formalize/engine.js +189 -0
  6. package/dist/formalize/engine.js.map +1 -0
  7. package/dist/formalize/validate.d.ts +15 -0
  8. package/dist/formalize/validate.d.ts.map +1 -0
  9. package/dist/formalize/validate.js +124 -0
  10. package/dist/formalize/validate.js.map +1 -0
  11. package/dist/llm/anthropic.d.ts +27 -0
  12. package/dist/llm/anthropic.d.ts.map +1 -0
  13. package/dist/llm/anthropic.js +86 -0
  14. package/dist/llm/anthropic.js.map +1 -0
  15. package/dist/llm/mock.d.ts +21 -0
  16. package/dist/llm/mock.d.ts.map +1 -0
  17. package/dist/llm/mock.js +29 -0
  18. package/dist/llm/mock.js.map +1 -0
  19. package/dist/llm/openai-compatible.d.ts +20 -0
  20. package/dist/llm/openai-compatible.d.ts.map +1 -0
  21. package/dist/llm/openai-compatible.js +46 -0
  22. package/dist/llm/openai-compatible.js.map +1 -0
  23. package/dist/llm/types.d.ts +11 -0
  24. package/dist/llm/types.d.ts.map +1 -0
  25. package/dist/llm/types.js +2 -0
  26. package/dist/llm/types.js.map +1 -0
  27. package/dist/mcp-server.d.ts +12 -0
  28. package/dist/mcp-server.d.ts.map +1 -0
  29. package/dist/mcp-server.js +446 -0
  30. package/dist/mcp-server.js.map +1 -0
  31. package/dist/skills/bm25.d.ts +22 -0
  32. package/dist/skills/bm25.d.ts.map +1 -0
  33. package/dist/skills/bm25.js +71 -0
  34. package/dist/skills/bm25.js.map +1 -0
  35. package/dist/skills/learner.d.ts +21 -0
  36. package/dist/skills/learner.d.ts.map +1 -0
  37. package/dist/skills/learner.js +123 -0
  38. package/dist/skills/learner.js.map +1 -0
  39. package/dist/skills/library.d.ts +36 -0
  40. package/dist/skills/library.d.ts.map +1 -0
  41. package/dist/skills/library.js +173 -0
  42. package/dist/skills/library.js.map +1 -0
  43. package/dist/skills/starters.d.ts +3 -0
  44. package/dist/skills/starters.d.ts.map +1 -0
  45. package/dist/skills/starters.js +381 -0
  46. package/dist/skills/starters.js.map +1 -0
  47. package/dist/skills/types.d.ts +54 -0
  48. package/dist/skills/types.d.ts.map +1 -0
  49. package/dist/skills/types.js +2 -0
  50. package/dist/skills/types.js.map +1 -0
  51. package/dist/solvers/correction-loop.d.ts +34 -0
  52. package/dist/solvers/correction-loop.d.ts.map +1 -0
  53. package/dist/solvers/correction-loop.js +52 -0
  54. package/dist/solvers/correction-loop.js.map +1 -0
  55. package/dist/solvers/prolog-solver.d.ts +3 -0
  56. package/dist/solvers/prolog-solver.d.ts.map +1 -0
  57. package/dist/solvers/prolog-solver.js +93 -0
  58. package/dist/solvers/prolog-solver.js.map +1 -0
  59. package/dist/solvers/session.d.ts +11 -0
  60. package/dist/solvers/session.d.ts.map +1 -0
  61. package/dist/solvers/session.js +25 -0
  62. package/dist/solvers/session.js.map +1 -0
  63. package/dist/solvers/types.d.ts +44 -0
  64. package/dist/solvers/types.d.ts.map +1 -0
  65. package/dist/solvers/types.js +2 -0
  66. package/dist/solvers/types.js.map +1 -0
  67. package/dist/solvers/z3-solver.d.ts +3 -0
  68. package/dist/solvers/z3-solver.d.ts.map +1 -0
  69. package/dist/solvers/z3-solver.js +81 -0
  70. package/dist/solvers/z3-solver.js.map +1 -0
  71. package/package.json +85 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,124 @@
1
+ # Chiasmus
2
+
3
+ MCP server that gives LLMs access to formal verification via Z3 (SMT solver) and Tau Prolog. Translates natural language problems into formal logic using a template-based pipeline, verifies results with mathematical certainty.
4
+
5
+ ## Setup
6
+
7
+ ```bash
8
+ npm install -g chiasmus
9
+ ```
10
+
11
+ ### Claude Code
12
+
13
+ ```bash
14
+ claude mcp add chiasmus -- npx chiasmus
15
+ ```
16
+
17
+ Or add to `~/.claude/settings.json`:
18
+
19
+ ```json
20
+ {
21
+ "mcpServers": {
22
+ "chiasmus": {
23
+ "command": "npx",
24
+ "args": ["chiasmus"]
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ ### Crush
31
+
32
+ Add to `crush.json`:
33
+
34
+ ```json
35
+ {
36
+ "mcp": {
37
+ "chiasmus": {
38
+ "type": "stdio",
39
+ "command": "npx",
40
+ "args": ["chiasmus"]
41
+ }
42
+ }
43
+ }
44
+ ```
45
+
46
+ ### OpenCode
47
+
48
+ Add to `opencode.json`:
49
+
50
+ ```json
51
+ {
52
+ "mcp": {
53
+ "chiasmus": {
54
+ "type": "local",
55
+ "command": ["npx", "chiasmus"]
56
+ }
57
+ }
58
+ }
59
+ ```
60
+
61
+ ## Tools
62
+
63
+ **`chiasmus_verify`** — Submit raw SMT-LIB or Prolog, get a verified result.
64
+
65
+ ```
66
+ chiasmus_verify solver="z3" input="
67
+ (declare-const x Int)
68
+ (declare-const y Int)
69
+ (assert (= (+ x y) 10))
70
+ (assert (> x 0))
71
+ (assert (> y 0))
72
+ "
73
+ → { status: "sat", model: { x: "7", y: "3" } }
74
+ ```
75
+
76
+ ```
77
+ chiasmus_verify solver="prolog"
78
+ input="parent(tom, bob). parent(bob, ann). ancestor(X,Y) :- parent(X,Y). ancestor(X,Y) :- parent(X,Z), ancestor(Z,Y)."
79
+ query="ancestor(tom, Who)."
80
+ → { status: "success", answers: [{ bindings: { Who: "bob" } }, { bindings: { Who: "ann" } }] }
81
+ ```
82
+
83
+ **`chiasmus_skills`** — Search the template library. Ships with 8 starter templates covering authorization, configuration, dependency resolution, validation, rule inference, and graph reachability.
84
+
85
+ **`chiasmus_formalize`** — Find the best template for a problem, get slot-filling instructions. Fill the slots using your context, then call `chiasmus_verify`.
86
+
87
+ **`chiasmus_solve`** — End-to-end: selects template, fills slots via LLM, runs lint and correction loops, returns a verified result. Optional — the same result is achieved by using `chiasmus_formalize` → fill slots → `chiasmus_verify`, which is the recommended workflow since the calling LLM has full conversation context.
88
+
89
+ **`chiasmus_learn`** — Extract a reusable template from a verified solution. Candidates get promoted after 3+ successful reuses.
90
+
91
+ ## Recommended Workflow
92
+
93
+ The calling LLM (Claude, GPT, etc.) drives the process — no API key needed:
94
+
95
+ 1. `chiasmus_formalize problem="Can our RBAC rules ever conflict?"` → get template + slot instructions
96
+ 2. Fill the template slots using your knowledge of the user's codebase
97
+ 3. `chiasmus_verify solver="z3" input="(filled spec)"` → get verified result
98
+ 4. If error → read the error, fix the spec, call `chiasmus_verify` again
99
+
100
+ ## When to Use
101
+
102
+ Use a solver when the LLM alone can't guarantee correctness:
103
+
104
+ - **"Does this hold for ALL inputs?"** — solvers prove universally, LLMs just check examples
105
+ - **"Do these rules ever conflict?"** — contradiction detection over combinatorial spaces
106
+ - **"Can X reach Y through any path?"** — transitive closure / reachability
107
+ - **Access control, configs, dependencies** — where correctness is non-negotiable
108
+
109
+ ## Configuration
110
+
111
+ | Variable | Default | Purpose |
112
+ |----------|---------|---------|
113
+ | `CHIASMUS_HOME` | `~/.chiasmus/` | Database and skill storage |
114
+ | `ANTHROPIC_API_KEY` | — | Optional: Anthropic provider for autonomous mode |
115
+ | `DEEPSEEK_API_KEY` | — | Optional: DeepSeek provider for autonomous mode |
116
+ | `OPENAI_API_KEY` | — | Optional: OpenAI provider for autonomous mode |
117
+ | `CHIASMUS_API_URL` | per provider | Override API base URL (e.g. for local models via Ollama) |
118
+ | `CHIASMUS_MODEL` | per provider | Override model name |
119
+
120
+ Providers are checked in order: Anthropic → DeepSeek → OpenAI. Only one key is needed for autonomous mode (`chiasmus_solve`, `chiasmus_learn`). When used from Claude Code, Crush, or OpenCode, no API key is needed — the calling LLM handles template filling directly.
121
+
122
+ ## License
123
+
124
+ Apache-2.0
@@ -0,0 +1,47 @@
1
+ import type { LLMAdapter } from "../llm/types.js";
2
+ import type { SkillLibrary } from "../skills/library.js";
3
+ import type { SkillTemplate } from "../skills/types.js";
4
+ import type { SolverResult, PrologAnswer } from "../solvers/types.js";
5
+ import type { CorrectionAttempt } from "../solvers/correction-loop.js";
6
+ /** Result of formalize() — template + instructions for the calling LLM */
7
+ export interface FormalizeResult {
8
+ template: SkillTemplate;
9
+ instructions: string;
10
+ }
11
+ /** Result of solve() — includes solver result + correction history */
12
+ export interface SolveResult {
13
+ result: SolverResult;
14
+ converged: boolean;
15
+ rounds: number;
16
+ history: CorrectionAttempt[];
17
+ templateUsed: string | null;
18
+ /** Convenience: extracted answers for Prolog results */
19
+ answers: PrologAnswer[];
20
+ }
21
+ export declare class FormalizationEngine {
22
+ private library;
23
+ private llm;
24
+ constructor(library: SkillLibrary, llm: LLMAdapter);
25
+ /**
26
+ * Formalize a problem: select a template and return it with
27
+ * fill instructions. Does NOT execute or call the LLM for filling.
28
+ */
29
+ formalize(problem: string): Promise<FormalizeResult>;
30
+ /**
31
+ * End-to-end solve: select template, ask LLM to fill slots,
32
+ * submit to solver with correction loop.
33
+ */
34
+ solve(problem: string, maxRounds?: number): Promise<SolveResult>;
35
+ private buildInstructions;
36
+ private llmFill;
37
+ private llmFix;
38
+ private buildSolverInput;
39
+ /**
40
+ * Lint loop: auto-fix what we can, then ask the LLM to fix remaining errors.
41
+ * Repeats until the spec passes validation or maxAttempts is reached.
42
+ */
43
+ private lintLoop;
44
+ /** Strip markdown fences and trim whitespace from LLM output */
45
+ private cleanResponse;
46
+ }
47
+ //# sourceMappingURL=engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/formalize/engine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAe,YAAY,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAGvE,0EAA0E;AAC1E,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,aAAa,CAAC;IACxB,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,sEAAsE;AACtE,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,YAAY,CAAC;IACrB,SAAS,EAAE,OAAO,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,iBAAiB,EAAE,CAAC;IAC7B,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,wDAAwD;IACxD,OAAO,EAAE,YAAY,EAAE,CAAC;CACzB;AA6BD,qBAAa,mBAAmB;IAE5B,OAAO,CAAC,OAAO;IACf,OAAO,CAAC,GAAG;gBADH,OAAO,EAAE,YAAY,EACrB,GAAG,EAAE,UAAU;IAGzB;;;OAGG;IACG,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC;IAU1D;;;OAGG;IACG,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,SAAI,GAAG,OAAO,CAAC,WAAW,CAAC;IAuCjE,OAAO,CAAC,iBAAiB;YAoCX,OAAO;YAUP,MAAM;IAwBpB,OAAO,CAAC,gBAAgB;IAsBxB;;;OAGG;YACW,QAAQ;IAuCtB,gEAAgE;IAChE,OAAO,CAAC,aAAa;CAMtB"}
@@ -0,0 +1,189 @@
1
+ import { correctionLoop } from "../solvers/correction-loop.js";
2
+ import { lintSpec } from "./validate.js";
3
+ const FORMALIZE_SYSTEM = `You are a formalization engine that translates natural language problems into formal logic specifications.
4
+
5
+ Your job:
6
+ 1. Read the problem description
7
+ 2. Read the template skeleton and slot descriptions
8
+ 3. Use the template as a STARTING POINT — fill the slots, but also adapt the structure if the problem requires it
9
+ 4. You may add extra variables, assertions, or rules beyond what the template defines
10
+ 5. You may remove or restructure parts of the skeleton that don't fit the specific problem
11
+ 6. Return ONLY the complete specification — no explanation, no markdown fences, no comments outside the spec
12
+
13
+ The template is guidance, not a constraint. The goal is a correct specification for the problem, not a rigid fill-in-the-blanks.
14
+
15
+ For Z3 (SMT-LIB): output valid SMT-LIB assertions. Do NOT include (check-sat) or (get-model).
16
+ For Prolog: output valid ISO Prolog facts and rules.
17
+
18
+ Be precise with syntax. The specification will be fed directly to a solver.`;
19
+ const FIX_SYSTEM = `You are a formal logic repair engine. You receive a specification that failed verification and the error message from the solver.
20
+
21
+ Fix the specification to resolve the error. Return ONLY the corrected specification — no explanation, no markdown fences.
22
+
23
+ Common issues:
24
+ - Type mismatches: ensure all comparisons use matching types
25
+ - Missing declarations: every constant must be declared before use
26
+ - Syntax errors: check parentheses, commas, periods
27
+ - For Prolog: ensure all clauses end with a period`;
28
+ export class FormalizationEngine {
29
+ library;
30
+ llm;
31
+ constructor(library, llm) {
32
+ this.library = library;
33
+ this.llm = llm;
34
+ }
35
+ /**
36
+ * Formalize a problem: select a template and return it with
37
+ * fill instructions. Does NOT execute or call the LLM for filling.
38
+ */
39
+ async formalize(problem) {
40
+ const results = this.library.search(problem, { limit: 1 });
41
+ const template = results.length > 0
42
+ ? results[0].template
43
+ : this.library.list()[0].template; // fallback to first template
44
+ const instructions = this.buildInstructions(problem, template);
45
+ return { template, instructions };
46
+ }
47
+ /**
48
+ * End-to-end solve: select template, ask LLM to fill slots,
49
+ * submit to solver with correction loop.
50
+ */
51
+ async solve(problem, maxRounds = 5) {
52
+ const { template } = await this.formalize(problem);
53
+ // Ask LLM to fill the template
54
+ let filledSpec = await this.llmFill(problem, template);
55
+ // Lint loop: auto-fix what we can, ask LLM to fix the rest
56
+ filledSpec = await this.lintLoop(filledSpec, template, maxRounds);
57
+ // Build solver input
58
+ const initialInput = this.buildSolverInput(template, filledSpec);
59
+ // Run correction loop with LLM as fixer
60
+ const correctionResult = await correctionLoop(initialInput, async (attempt, error) => {
61
+ const fixed = await this.llmFix(attempt, error, template);
62
+ // Lint the fix before resubmitting to the solver
63
+ const linted = await this.lintLoop(fixed, template, 2);
64
+ return this.buildSolverInput(template, linted);
65
+ }, { maxRounds });
66
+ // Record template use
67
+ this.library.recordUse(template.name, correctionResult.converged);
68
+ return {
69
+ result: correctionResult.result,
70
+ converged: correctionResult.converged,
71
+ rounds: correctionResult.rounds,
72
+ history: correctionResult.history,
73
+ templateUsed: template.name,
74
+ answers: correctionResult.result.status === "success"
75
+ ? correctionResult.result.answers
76
+ : [],
77
+ };
78
+ }
79
+ buildInstructions(problem, template) {
80
+ const slotDescs = template.slots
81
+ .map((s) => ` {{SLOT:${s.name}}} — ${s.description}\n Example: ${s.format}`)
82
+ .join("\n\n");
83
+ // Find matching normalization guidance
84
+ const normGuidance = template.normalizations
85
+ .map((n) => ` - ${n.source}: ${n.transform}`)
86
+ .join("\n");
87
+ const queryNote = template.solver === "prolog"
88
+ ? `\n\nPROLOG QUERY: After filling the template, you will also need to provide a Prolog query goal (ending with a period) that asks the question implied by the problem.`
89
+ : "";
90
+ return `TEMPLATE: ${template.name} (${template.solver})
91
+ DESCRIPTION: ${template.signature}
92
+
93
+ SKELETON:
94
+ ${template.skeleton}
95
+
96
+ SLOTS TO FILL:
97
+ ${slotDescs}
98
+
99
+ NORMALIZATION GUIDANCE:
100
+ ${normGuidance}
101
+ ${queryNote}
102
+
103
+ PROBLEM: ${problem}
104
+
105
+ Fill each {{SLOT:name}} in the skeleton with appropriate ${template.solver === "z3" ? "SMT-LIB" : "Prolog"} code.
106
+ The template is a STARTING POINT — adapt the structure if the problem requires it.
107
+ You may add extra variables, assertions, or rules. You may remove or restructure parts that don't fit.
108
+ ${template.solver === "z3" ? "Do NOT include (check-sat) or (get-model) — the tool adds these automatically." : "Ensure all clauses end with a period."}
109
+ Return only the complete filled specification.`;
110
+ }
111
+ async llmFill(problem, template) {
112
+ const instructions = this.buildInstructions(problem, template);
113
+ const response = await this.llm.complete(FORMALIZE_SYSTEM, [
114
+ { role: "user", content: instructions },
115
+ ]);
116
+ return this.cleanResponse(response);
117
+ }
118
+ async llmFix(attempt, error, template) {
119
+ const spec = attempt.type === "z3" ? attempt.smtlib : attempt.program;
120
+ const response = await this.llm.complete(FIX_SYSTEM, [
121
+ {
122
+ role: "user",
123
+ content: `SOLVER: ${template.solver}
124
+ SPECIFICATION:
125
+ ${spec}
126
+
127
+ ERROR:
128
+ ${error}
129
+
130
+ Fix the specification and return only the corrected version.`,
131
+ },
132
+ ]);
133
+ return this.cleanResponse(response);
134
+ }
135
+ buildSolverInput(template, spec) {
136
+ if (template.solver === "z3") {
137
+ return { type: "z3", smtlib: spec };
138
+ }
139
+ // For Prolog, extract ?- query from the last line that starts with ?-
140
+ const lines = spec.split("\n");
141
+ let program = spec;
142
+ let query = "true.";
143
+ for (let i = lines.length - 1; i >= 0; i--) {
144
+ const trimmed = lines[i].trim();
145
+ if (trimmed.startsWith("?-")) {
146
+ query = trimmed.replace(/^\?\-\s*/, "");
147
+ program = lines.slice(0, i).join("\n").trim();
148
+ break;
149
+ }
150
+ }
151
+ return { type: "prolog", program, query };
152
+ }
153
+ /**
154
+ * Lint loop: auto-fix what we can, then ask the LLM to fix remaining errors.
155
+ * Repeats until the spec passes validation or maxAttempts is reached.
156
+ */
157
+ async lintLoop(spec, template, maxAttempts) {
158
+ let current = spec;
159
+ const seenErrors = new Set();
160
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
161
+ const lint = lintSpec(current, template.solver);
162
+ current = lint.spec; // apply auto-fixes
163
+ if (lint.errors.length === 0) {
164
+ return current; // clean — ready for solver
165
+ }
166
+ // Detect oscillation: if we've seen these exact errors before, bail out
167
+ const errorKey = lint.errors.sort().join("|");
168
+ if (seenErrors.has(errorKey)) {
169
+ return current; // LLM is repeating itself — let the solver try
170
+ }
171
+ seenErrors.add(errorKey);
172
+ // Ask LLM to fix the remaining errors
173
+ const errorReport = [
174
+ ...lint.fixes.map((f) => `[auto-fixed] ${f}`),
175
+ ...lint.errors.map((e) => `[error] ${e}`),
176
+ ].join("\n");
177
+ current = await this.llmFix(this.buildSolverInput(template, current), `Lint errors (fix these before solver submission):\n${errorReport}`, template);
178
+ }
179
+ return current;
180
+ }
181
+ /** Strip markdown fences and trim whitespace from LLM output */
182
+ cleanResponse(response) {
183
+ return response
184
+ .replace(/^```(?:smt-lib|smtlib|smt|prolog|pl)?\n?/gm, "")
185
+ .replace(/^```\n?/gm, "")
186
+ .trim();
187
+ }
188
+ }
189
+ //# sourceMappingURL=engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/formalize/engine.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAE/D,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAmBzC,MAAM,gBAAgB,GAAG;;;;;;;;;;;;;;;4EAemD,CAAC;AAE7E,MAAM,UAAU,GAAG;;;;;;;;mDAQgC,CAAC;AAEpD,MAAM,OAAO,mBAAmB;IAEpB;IACA;IAFV,YACU,OAAqB,EACrB,GAAe;QADf,YAAO,GAAP,OAAO,CAAc;QACrB,QAAG,GAAH,GAAG,CAAY;IACtB,CAAC;IAEJ;;;OAGG;IACH,KAAK,CAAC,SAAS,CAAC,OAAe;QAC7B,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;QAC3D,MAAM,QAAQ,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC;YACjC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ;YACrB,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,6BAA6B;QAElE,MAAM,YAAY,GAAG,IAAI,CAAC,iBAAiB,CAAC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ACD,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YAEzB,sCAAsC;YACtC,MAAM,WAAW,GAAG;gBAClB,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC,EAAE,CAAC;gBAC7C,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC;aAC1C,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAEb,OAAO,GAAG,MAAM,IAAI,CAAC,MAAM,CACzB,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,OAAO,CAAC,EACxC,sDAAsD,WAAW,EAAE,EACnE,QAAQ,CACT,CAAC;QACJ,CAAC;QAED,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,gEAAgE;IACxD,aAAa,CAAC,QAAgB;QACpC,OAAO,QAAQ;aACZ,OAAO,CAAC,4CAA4C,EAAE,EAAE,CAAC;aACzD,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;aACxB,IAAI,EAAE,CAAC;IACZ,CAAC;CACF"}
@@ -0,0 +1,15 @@
1
+ import type { SolverType } from "../solvers/types.js";
2
+ export interface LintResult {
3
+ /** The spec after auto-fixes have been applied */
4
+ spec: string;
5
+ /** Auto-fixes that were applied */
6
+ fixes: string[];
7
+ /** Remaining errors that need LLM intervention */
8
+ errors: string[];
9
+ }
10
+ /**
11
+ * Lint and auto-fix a specification before sending to the solver.
12
+ * Fixes what it can, reports what it can't.
13
+ */
14
+ export declare function lintSpec(spec: string, solver: SolverType): LintResult;
15
+ //# sourceMappingURL=validate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.d.ts","sourceRoot":"","sources":["../../src/formalize/validate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD,MAAM,WAAW,UAAU;IACzB,kDAAkD;IAClD,IAAI,EAAE,MAAM,CAAC;IACb,mCAAmC;IACnC,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,kDAAkD;IAClD,MAAM,EAAE,MAAM,EAAE,CAAC;CAClB;AAED;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,UAAU,CAmCrE"}