typeglish 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 (51) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +13 -0
  3. package/README.md +301 -0
  4. package/dist/chunk-3NQ3VYO6.js +566 -0
  5. package/dist/chunk-3NQ3VYO6.js.map +1 -0
  6. package/dist/chunk-KRYC4OTL.js +3573 -0
  7. package/dist/chunk-KRYC4OTL.js.map +1 -0
  8. package/dist/chunk-NLQIL5WD.js +25 -0
  9. package/dist/chunk-NLQIL5WD.js.map +1 -0
  10. package/dist/chunk-PR4QN5HX.js +39 -0
  11. package/dist/chunk-PR4QN5HX.js.map +1 -0
  12. package/dist/chunk-PXAMTGYY.js +3 -0
  13. package/dist/chunk-PXAMTGYY.js.map +1 -0
  14. package/dist/chunk-VMACILYN.js +140 -0
  15. package/dist/chunk-VMACILYN.js.map +1 -0
  16. package/dist/chunk-Y64EAEYB.js +10919 -0
  17. package/dist/chunk-Y64EAEYB.js.map +1 -0
  18. package/dist/chunk-YH4ZLQ4G.js +4260 -0
  19. package/dist/chunk-YH4ZLQ4G.js.map +1 -0
  20. package/dist/chunk-ZKMHZHID.js +56 -0
  21. package/dist/chunk-ZKMHZHID.js.map +1 -0
  22. package/dist/cli.d.ts +1 -0
  23. package/dist/cli.js +447 -0
  24. package/dist/cli.js.map +1 -0
  25. package/dist/compile-DViQS2oG.d.ts +310 -0
  26. package/dist/diagnostics-BWJ_oMd8.d.ts +49 -0
  27. package/dist/exhaustiveness-VBVWCX5W.js +123 -0
  28. package/dist/exhaustiveness-VBVWCX5W.js.map +1 -0
  29. package/dist/index-Df_QnTgq.d.ts +313 -0
  30. package/dist/index.d.ts +3 -0
  31. package/dist/index.js +7 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/mcp.d.ts +11 -0
  34. package/dist/mcp.js +36378 -0
  35. package/dist/mcp.js.map +1 -0
  36. package/dist/monaco.css +46 -0
  37. package/dist/monaco.d.ts +43 -0
  38. package/dist/monaco.js +971 -0
  39. package/dist/monaco.js.map +1 -0
  40. package/dist/node.d.ts +21 -0
  41. package/dist/node.js +8 -0
  42. package/dist/node.js.map +1 -0
  43. package/dist/spell-node.d.ts +8 -0
  44. package/dist/spell-node.js +23 -0
  45. package/dist/spell-node.js.map +1 -0
  46. package/dist/spell.d.ts +18 -0
  47. package/dist/spell.js +4 -0
  48. package/dist/spell.js.map +1 -0
  49. package/dist/z3-MWU3GSVT.js +5 -0
  50. package/dist/z3-MWU3GSVT.js.map +1 -0
  51. package/package.json +160 -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/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ TypeGlish
2
+ Copyright (c) 2026 Voiceflow, Inc.
3
+
4
+ This product includes rule lexicons and detection-pattern families adapted from
5
+ PromptLint (https://www.promptlint.dev/), licensed under the Apache License,
6
+ Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0). The hedge/vagueness
7
+ word lists (src/core/diagnostics.ts) and the leaked-secret / injection pattern
8
+ families (src/core/security.ts) were reimplemented natively for TypeGlish.
9
+
10
+ The optimizer in src/core/gepa/ implements the GEPA algorithm (Genetic-Pareto
11
+ reflective prompt evolution) described in arXiv:2507.19457, with the reference
12
+ implementation at https://github.com/gepa-ai/gepa (MIT License). The TypeScript
13
+ implementation here is original code.
package/README.md ADDED
@@ -0,0 +1,301 @@
1
+ # TypeGlish
2
+
3
+ > **Turning English into logically consistent, controlled, maintainable, executable programs for LLMs.**
4
+
5
+ A controlled language with the rigor of a programming language — operators, declarations, types, and a
6
+ static consistency checker — that compiles English to clean, XML-tagged prompts. Think *the TypeScript
7
+ of English*: you still write English, but a grammar, a type system, and a solver have your back.
8
+
9
+ The long-term goal: make English **safe for agents to work with** — a static analyzer for the
10
+ instructions, policies, and knowledge agents consume, run at corpus scale to catch contradictions the
11
+ way a compiler does for code. This repo is **the rules and the compiler** for TypeGlish, plus a
12
+ playground to build and work on the language. See **[ROADMAP.md](ROADMAP.md)** for where it's headed.
13
+
14
+ ## Why
15
+
16
+ A prompt is a program written in English — but English has no compiler. Nothing tells you when
17
+ two instructions contradict each other, when a constraint is impossible to satisfy, or when a
18
+ reference is undefined. TypeGlish adds that missing layer.
19
+
20
+ ```typeglish
21
+ Persona IS a customer support agent for Acme.
22
+
23
+ # Role
24
+ "You are @{Persona}."
25
+
26
+ # Constraints
27
+ - NEVER state a specific price; ALWAYS direct pricing questions to sales.
28
+ - MUST keep every response to at most 3 sentences.
29
+ - IF you are unsure THEN say so AND offer to escalate.
30
+ ```
31
+
32
+ - **Operators** — modals (`MUST` / `NEVER` / `SHOULD` …), control flow (`IF … THEN … OTHERWISE`),
33
+ connectives (`AND` / `OR` / `NOT`), and the copula (`IS` / `ARE` / `AM`). Case-insensitive.
34
+ - **Statement terminators** — every statement ends with `.` `!` `?` (a lead-in may end with `:`);
35
+ unterminated is a **compile error**, one-click fixable — the semicolon rule, one level up. The
36
+ terminator never leaks into a bound value: `Tone IS warm.` binds `warm`.
37
+ - **Layout is syntax** — the indent unit is 2 spaces and **indentation mirrors section nesting**
38
+ (a nested tag one unit deeper, its content one deeper than that); one space between things.
39
+ Alignment columns, trailing whitespace, and tabs are **compile errors** with one-click fixes — "LLM
40
+ spacing" doesn't compile. Blank lines, by contrast, are free: **the compiler packs the emitted prompt**
41
+ — consecutive prose statements join onto one line, a run of blank lines collapses to a single break, and
42
+ structure (lists, headings, tags, fences) keeps its own line. Fences and literal zones stay verbatim,
43
+ and cosmetic indent is stripped at compile, so the model reads clean packed text either way.
44
+ - **A strict character set** — the instruction plane is plain ASCII text: em-dashes, curly quotes,
45
+ arrows, bullets, math symbols, emoji, and invisible characters are **compile errors** with
46
+ one-click ASCII fixes. Not aesthetics: each mark hides meaning from the checker (a curly
47
+ apostrophe conceals a possession contradiction; `≤ 3` hides the bound `at most 3` proves).
48
+ Human language never flags — accents, scripts, currency stay legal — and symbols keep their
49
+ literal homes (`<examples>`, `<"…">` zones, fences, quotes).
50
+ - **Declarations** — `Persona IS a support agent` defines a reusable object; `{Persona}` expands it
51
+ (references resolve case-insensitively).
52
+ - **Types** — `Animals ARE one of alligator, orangutan` declares a closed, mutually-exclusive set.
53
+ - **String literals** — `"…"` escapes to literal prose: no operators parsed inside, quotes stripped
54
+ on compile, `@{refs}` still expand.
55
+ - **Sections & structure** — group with `#` headings or `<xml_tags>` (same-line and inline content
56
+ welcome); `<$name>` strips control-plane scaffolding, `<?name>` strips just the wrapper tag,
57
+ `<"name">` keeps its body **verbatim** (a literal zone for reference tables and syntax samples —
58
+ quotes are the one escape, here at section scale), and `<examples>` is the literal zone by name. Structure is enforced: content must live in a
59
+ section, `#` headings must sit inside XML sections once you use any, and section names must be
60
+ **distinct and meaningful** — duplicate/near-duplicate names error, vague ones warn.
61
+ - **Definition lists** — `term:: definition` rows for glossaries and cheat-sheets: position-insensitive
62
+ to author (agents never break alignment), parse-literal (samples inside never open zones or bind) yet
63
+ **content-checked** — one statement per line holds inside a body (the editor wraps; a hard-wrapped
64
+ continuation is a compile error), terminators and the character set apply — and the compiler owns
65
+ the emitted layout (nested sub-bullets, fenced samples) so the model reads clean markdown regardless
66
+ of authoring; duplicate terms flagged.
67
+ - **Statement annotations & references** — `@@ a note` documents the statement below it (a docstring
68
+ that compiles away and is inert to every analysis tier); `@@ name: …` also **names** that statement.
69
+ References are typed sigils, each validated at compile time: `@{variable}` reads host state,
70
+ `@<section>` inlines a section, `@[tool]` references a tool — inline it emits the checked bare
71
+ name, alone on a line it surfaces `name — description` (a dangling reference is an error, and an
72
+ exact tool name in bare prose is too: point it or quote it).
73
+ - **A consistency checker** — propositional + SMT (Z3). Catches `MUST escalate` vs `NEVER escalate`,
74
+ and numeric contradictions like `at most 3 sentences` vs `at least 5 sentences` that propositional
75
+ logic provably can't decide. Its **quantifier layer** gives the English of quantity its logic:
76
+ the square of opposition (`all` / `some` / `no` / `most` / `only`), set sizes (`there is only one
77
+ tool` vs `there are many tools`; nouns fold by lemma, so `people` ⇄ `person`), action counts
78
+ (`call five tools` vs `call six tools` — one count per directive slot), supply vs demand
79
+ (`there is only one tool` vs `call five tools`), definite reference (`the tool` with two tools
80
+ declared), and transitive syllogism chains. Claims key by what they are about (noun + restrictor
81
+ tail); frame, subject, and owner are refinement fields that must agree where present but never
82
+ exempt a claim from checking. Directives default to the ADDRESSEE — a bare rule, `You must…`, a
83
+ declared alias (`You are Claude.` → `Claude must…`), and a declared role (`You are a support
84
+ agent.` → `the support agent must…`) are one subject's rules, while an undeclared `the assistant`
85
+ stays scoped (no guessing; opt nouns in via glish.tgc `$CONFIG addressee one of …`) and `the user` is
86
+ never you. Guards parse in both spellings — `IF … THEN …` and the comma form English writes
87
+ (`If the user is angry, never quote prices.`); `Don't` reads as `DO NOT`.
88
+ - **A predicate system** — actions parse into `verb + theme + roles + tool binding` against a curated
89
+ catalog, so the checker also proves verb-level facts: synonyms merge (`output`/`print`), antonyms
90
+ conflict (`MUST output` vs `MUST suppress` flips the badge), bare imperatives are obligations, and
91
+ `fire book_appointment` ≡ `call book_appointment`.
92
+ - **A semantic auditor (advisory)** — per-line **residual value** and **overlap**, scored at the atom
93
+ level by a local NLI model with an LLM-judge escalation (every verdict distilled as training data
94
+ for an offline replacement). Heavy duplication warns; proposed cuts are behaviorally verified;
95
+ a greedy reducer consolidates toward a minimal, orthogonal prompt.
96
+ - **The TG score** — one proof-backed number per prompt (`tg score`, CI-gateable with `--min B`).
97
+ Proven errors **gate** to F; graded facets measure enforceability (the checker's own visibility),
98
+ consistency, structure, **annotation coverage** (every statement should carry a `@@` note saying
99
+ what it's for), style, security, and density; every deducted point cites a finding + fix
100
+ (the ledger is the to-do list). Calibrated against an authored good/bad corpus with a tested
101
+ separation margin.
102
+ - **`$TEST` — the file carries its own eval suite** — cases whose `- input::` / `- expect::` bullets
103
+ live beside the rules they test, or in an auto-discovered sibling `<name>.test.tg`, and compile away
104
+ entirely. Deterministic asserts (`contains`, `matches`, `at most N sentences`) are code-checked; prose
105
+ expectations are judge-scored. Run them with `tg test`; feeds coverage (`prompt/untested-rule`), the
106
+ profile, promptfoo emit, portability, and the optimizer.
107
+ - **`$EXAMPLE` — the file carries its own few-shot** — one exchange per block (`- input::` / `- good::`,
108
+ optional `- bad::`), the same bullet record. Each `- good::` compiles into the prompt as a labelled
109
+ few-shot exchange; `- bad::` is held out — never shown to the model, so it can't be imitated. A
110
+ malformed block is a `structure/bad-example` error.
111
+ - **The profile** — per-statement attribution, keyed by content hash (survives comments, reordering;
112
+ an edited statement is a new hash, so staleness is impossible): what a line says (IR, predicates),
113
+ what duplicates it (residual), which cases exercise it, and the measured ablation **Δ per case**
114
+ (`tg profile --behavioral`, budget-confirmed). Those fold into a per-statement **verdict** — potency
115
+ (Δ) crossed with redundancy (residual) and coverage → **keep / cut** (implied or dead) **/ test**, with
116
+ attribution and honest degradation when a tier hasn't run. `tg annotate` writes it into the margin as
117
+ `//@` machine comments — compile-stripped, human comments untouched; the editor shows it on hover.
118
+ - **Portability, measured** — `tg portability` runs the suite across a model panel (promptfoo owns
119
+ the matrix; TypeGlish owns zero dependencies) and reports cross-model agreement WITH per-model
120
+ pass rates beside it — consistency ≠ correctness is encoded, not footnoted.
121
+ - **A dependency map** — the playground's **Map** view renders the prompt as the graph it already is:
122
+ the depended-upon symbols (inputs with their domains, tools, variables, tests) on one side, the
123
+ section skeleton with a reference chip on every wired line on the other, and hover to light up an
124
+ edge — where a symbol is used, or what a line depends on. Broken edges (a `<closing>` that resolves
125
+ to nothing, an unused import) are marked in place, from the **same resolution engine as the
126
+ squiggles**, so the map can never disagree with the checker. Deterministic and free.
127
+ - **A fix list, ranked by score impact** — the playground's **Fixes** panel is the score ledger made
128
+ actionable: every deduction below 100, ordered by the points it costs, pinned to its line, with a
129
+ one-click fix where one exists. Deterministic and free — it updates as you type, and it never
130
+ spends a model call. This is "highlight what needs changing," computed, not judged.
131
+ - **A GEPA optimizer with the compiler in the loop** — `tg optimize` (a deliberate CLI opt-in — the
132
+ editor highlights, the human changes) runs reflective prompt evolution (per-instance Pareto,
133
+ minibatch acceptance) where provably-broken mutants are rejected **free** before any eval spend,
134
+ mutants that touch their own `$TEST` blocks are rejected as fitness hacking, and the accept rule
135
+ breaks ties toward **fewer tokens** — the bloat spiral of naive optimization loops structurally
136
+ loses. Every model call (evals AND reflections) is charged against the budget, so the pre-run
137
+ quote is a hard spend ceiling; the result lands as a new `.optimized.tg`, never overwriting the seed.
138
+ - **Conditionals, resolved** — deterministic `IF` chains / guarded sections make a prompt a template: `(source, state)
139
+ → prompt`. Two stages, one seam (`prepareTemplate`): **render** is state-free and *total* — an
140
+ unresolved chain compiles to conditional English (`If voice is true: … / Otherwise: …`), never a
141
+ leaked sigil; **resolve** is state-dependent and *partial* — it collapses only the branches the bag
142
+ can decide. The playground's **values panel** exposes it: set an input and the Compiled view resolves
143
+ that chain to the one branch the model gets; leave it unset and it stays conditional.
144
+ - **A compiler** — `text → parse → IR → check → XML`: references expand, declarations and comments
145
+ strip, and each `# block` becomes a semantic tag (`<role>`, `<constraints>`, …).
146
+ - **Agent files** — a single `.tg` file can be a whole agent: `$CONFIG` sets the model and settings,
147
+ `$TOOL` / `$SERVICE` define tools as YAML-shaped code with HTTP bindings, and `compile()` emits the
148
+ prompt **plus** an agent bundle (settings + JSON-Schema tool definitions). `npm run tg:run agent.tg`
149
+ runs it live — tool-use loop, bindings, and `{env.*}` secrets included.
150
+
151
+ The full language reference is in **[SPEC.md](SPEC.md)**.
152
+
153
+ ## The repo
154
+
155
+ ```
156
+ src/core/ the language + compiler (pure TS — runs in Node, browser, and tests alike)
157
+ typeglish-grammar.ts the grammar (Peggy / PEG)
158
+ parser.ts, ast.ts parse a clause → statement AST
159
+ ir.ts lower the AST → logical-form IR (directives, conditions, numeric bounds)
160
+ prompt.ts the compiler: declarations, references, quotes, comments, render
161
+ compile.ts render → semantic XML + the agent bundle
162
+ tool.ts $TOOL / $SERVICE definitions (tool schemas + HTTP bindings)
163
+ agent.ts the runner: the tool-use loop + HTTP bindings (Node-side, like z3)
164
+ solver/z3.ts the SMT consistency checker (deontic + numeric)
165
+ predicate.ts, verbs.ts the predicate system: action parser + the curated verb catalog
166
+ semantic/ the advisory tier: atoms, NLI engine, judge + distillation, reducer
167
+ src/lib/ the published surface — the `typeglish` bin (check / build / score / resolve /
168
+ reference / mcp / claude-hook), build.ts (artifact + hash manifest), deploy-gate.ts,
169
+ claude-hook.ts, project.ts (glish.tgc discovery), `typeglish/monaco`, `typeglish/spell`
170
+ src/mcp/ the MCP head — `typeglish mcp`: five stateless tools over stdio, results
171
+ byte-shaped like the CLI --json (the LSP pattern, one transport over)
172
+ lsp/ the stdio LSP head (editor language services)
173
+ plugin/ the Claude Code plugin — skill + PostToolUse check hook + PreToolUse deploy gate
174
+ (served by .claude-plugin/marketplace.json at the repo root)
175
+ docs/agents/ TYPEGLISH.md — the GENERATED agent language reference (AGENTS.md-style consumers)
176
+ src/web/ the playground — a Monaco editor that consumes `src/lib` (it's the first consumer)
177
+ server/ the Node side (LLM calls + the server-side Z3 logic check) as Vite middleware
178
+ ```
179
+
180
+ **Changing the language?** Every operator, type, character rule, and diagnostic code lives in exactly one
181
+ **single-source-of-truth** module — see the **SSOT registry** in [`CLAUDE.md`](CLAUDE.md) (invariant #1). Edit
182
+ the SSOT, run `npm run gen:syntax`, and let the drift-lock tests tell you what else to update; a hardcoded copy
183
+ anywhere else fails CI.
184
+
185
+ ## Install
186
+
187
+ Zero-setup — the CLI has **no runtime dependencies**, so `npx` cold-starts in seconds:
188
+
189
+ ```bash
190
+ npx typeglish check prompts/*.tg [--json] # exit 1 on any provable error
191
+ npx typeglish build prompts/*.tg # passing files → .typeglish/dist/*.txt artifacts
192
+ # + a hash manifest (.typeglish/build-manifest.json)
193
+ npx typeglish score prompt.tg --min B # the TG score; exit 1 below the floor (the CI gate)
194
+ npx typeglish resolve prompt.tg --vars '{"tier":"premium"}'
195
+ npx typeglish --explain logic/contradiction # what any diagnostic code means
196
+ npx typeglish mcp # the same tools over MCP stdio (for shell-less agent hosts)
197
+ ```
198
+
199
+ `build` is the deploy contract: the artifact — `compile(source).xml` — is what a prompt-taking system
200
+ (a system prompt, an assistant API, Voiceflow) should receive, and the manifest proves any payload
201
+ byte-for-byte ("this exact prompt came out of a passing compile"). A file with a blocking error
202
+ refuses to build; nothing failing can enter the manifest.
203
+
204
+ In a project, install it and add the proof tiers you want — both are optional peers, and the
205
+ deterministic core works identically without them:
206
+
207
+ ```bash
208
+ npm i -D typeglish
209
+ npm i -D z3-solver # + SMT proofs (contradictions, unsatisfiable bounds)
210
+ npm i -D nspell dictionary-en dictionary-en-gb # + spell-check (the typeglish/spell module)
211
+ ```
212
+
213
+ Without `z3-solver`, `check` runs the synchronous tier (still the full language/consistency/structure
214
+ check); with it, the same command adds the Z3 numeric + exhaustiveness proofs. Requires Node ≥ 20.19.
215
+
216
+ ## Embed in your product (Monaco)
217
+
218
+ Any product with a Monaco editor gets the full TypeGlish experience — syntax highlighting,
219
+ the object-record hover, completion, live consistency squiggles, object-reference
220
+ highlighting, and list/operator authoring — in a couple of calls:
221
+
222
+ ```ts
223
+ import * as monaco from 'monaco-editor';
224
+ import { setupTypeGlish, attachTypeGlish } from 'typeglish/monaco';
225
+ import 'typeglish/monaco.css';
226
+
227
+ setupTypeGlish(monaco); // once per monaco instance
228
+ const editor = monaco.editor.create(el, { language: 'typeglish', theme: 'typeglish-dark' });
229
+ attachTypeGlish(monaco, editor); // per editor → squiggles, highlights, authoring
230
+ ```
231
+
232
+ Need just the compiler (no editor)? The core runs anywhere — Node or browser:
233
+
234
+ ```ts
235
+ import { compile } from 'typeglish';
236
+ const { diagnostics, consistent, xml } = compile(source);
237
+ ```
238
+
239
+ Every rule lives in the framework-agnostic core; `typeglish/monaco` only wires it to Monaco's
240
+ APIs. The playground in `src/web/` is the first consumer of exactly this surface.
241
+
242
+ ## Develop
243
+
244
+ ```bash
245
+ npm install
246
+ npm run dev # the playground at http://localhost:5273
247
+ npm run typecheck
248
+ npm test # ~2,200 unit tests cover the language, checker, score, and semantic kernel
249
+ npm run check -- prompt.tg [--json] # compiler errors + warnings, agent-friendly (exit 1 on errors)
250
+ npm run score -- prompt.tg [--full] [--min B] # the TG score + ledger (exit 1 below --min: the CI gate)
251
+ npm run tg:test -- prompt.tg [--dry] [--min 0.7] # run the suite (inline + sibling .test.tg): per-case pass/fail
252
+ npm run fmt -- prompt.tg [--write] # join wrapped fragments, split compound rules
253
+ npm run profiles -- prompt.tg [--behavioral --yes] # per-statement attribution (static free; Δ costs, confirmed)
254
+ npm run annotate -- prompt.tg [--write|--clean] # write the profile into //@ margin comments
255
+ npm run emit -- promptfoo prompt.tg # the file's $TEST suite as a promptfoo config
256
+ npm run portability -- prompt.tg --models a,b # cross-model agreement (then --results out.json)
257
+ npm run optimize -- prompt.tg --budget 24 [--estimate] [--json] # GEPA; --estimate quotes cost (free), --json = agent-readable result
258
+ npm run semantic -- prompt.tg # per-line residual/overlap audit (add --reduce, --actions)
259
+ npm run semantic:bench # regenerate the golden-pair benchmark report
260
+ ```
261
+
262
+ The compiler core has no browser dependencies, so the grammar, the IR, and the solver behave
263
+ identically in Node, the browser, and Vitest.
264
+
265
+ ## Agents in the loop
266
+
267
+ The compiler talks back to agents at the moment their work SETTLES — the turn boundary — never
268
+ mid-typing (half-written text is legitimately broken). The mental model everywhere is **TypeScript for
269
+ prompts**: the `.tg` is source in git, the deployed prompt is a build artifact, and the gate between
270
+ them is mechanical.
271
+
272
+ - **In Claude Code**, install the plugin and the whole loop runs itself:
273
+
274
+ ```
275
+ /plugin marketplace add Bradenream/TypeGlish
276
+ /plugin install typeglish@typeglish
277
+ ```
278
+
279
+ - A **skill** teaches the workflow — author `.tg` → check → score → build → deploy the artifact
280
+ verbatim — with the generated language reference as its deep material.
281
+ - A **PostToolUse hook** re-checks every settled `.tg` edit and feeds blocking diagnostics straight
282
+ back to the model as fix-now feedback (advisories ride along as context; clean files stay silent).
283
+ - A **PreToolUse deploy gate** hashes outgoing prompt payloads (Voiceflow MCP tools by default;
284
+ configurable via `.typeglish/deploy-gate.json`) against `.typeglish/build-manifest.json`: a prompt
285
+ no passing build produced is **denied** with the fix in the message, and a verified one still goes
286
+ through the normal permission flow — the gate never auto-approves. Escape hatches:
287
+ `TYPEGLISH_DEPLOY_GATE=off|ask`.
288
+ - **In the playground**, the Copilot gets a **turn-end compiler report**: when its edits land, the
289
+ merged diagnostics are diffed against the turn-start snapshot and reported — as a ⚙ row in the
290
+ transcript and as compiler truth in the model's history. A turn that *introduced* errors triggers
291
+ one automatic fix round (toggleable, never recursive).
292
+ - **Any other agent with a shell** (Cursor, a CI bot, …) gets the same truth from
293
+ `npx typeglish check|score|build --json` — data on stdout, diagnostics on stderr, exit codes as
294
+ gates, `typeglish --explain <code>` for what any code means. Wire the same loop into any hook system.
295
+ - **Shell-less hosts** (claude.ai, any MCP client) get the compiler as five MCP tools —
296
+ `npx -y typeglish mcp` — check / build / score / explain / reference, results byte-identical to the
297
+ CLI's `--json`. A host with no filesystem passes `source` inline; `build` returns the artifact + its
298
+ sha256 without persisting.
299
+ - **Teaching the language**: `typeglish reference` prints the generated agent reference
300
+ ([docs/agents/TYPEGLISH.md](docs/agents/TYPEGLISH.md) is the same document, committed for
301
+ AGENTS.md-style consumers), so an agent that has never seen TypeGlish can learn it in one read.