intentumdiff-python 0.0.1__py3-none-manylinux_2_39_x86_64.whl

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 (165) hide show
  1. intentumdiff/__init__.py +134 -0
  2. intentumdiff/_differ_gate.py +210 -0
  3. intentumdiff/_differ_presentation.py +786 -0
  4. intentumdiff/_differ_runtime.py +320 -0
  5. intentumdiff/analysis/__init__.py +1 -0
  6. intentumdiff/analysis/compile_commands.py +151 -0
  7. intentumdiff/analysis/cross_file.py +71 -0
  8. intentumdiff/analysis/diagnostics.py +309 -0
  9. intentumdiff/analysis/guardrail_reports.py +254 -0
  10. intentumdiff/analysis/guardrails.py +318 -0
  11. intentumdiff/analysis/invariances.py +1207 -0
  12. intentumdiff/analysis/keyed_profiles.py +25 -0
  13. intentumdiff/analysis/resource_profiles.py +14 -0
  14. intentumdiff/analysis/schema_resolver.py +816 -0
  15. intentumdiff/analysis/text_review.py +46 -0
  16. intentumdiff/analysis/user_schemas.py +430 -0
  17. intentumdiff/assets.py +45 -0
  18. intentumdiff/cache/__init__.py +37 -0
  19. intentumdiff/cache/duckdb_store.py +98 -0
  20. intentumdiff/cache/sqlite_store.py +149 -0
  21. intentumdiff/cache/store.py +190 -0
  22. intentumdiff/cli/__init__.py +199 -0
  23. intentumdiff/cli/_commands.py +2141 -0
  24. intentumdiff/cli/_parser.py +1061 -0
  25. intentumdiff/cli/_shared.py +644 -0
  26. intentumdiff/content_type.py +59 -0
  27. intentumdiff/core/__init__.py +1 -0
  28. intentumdiff/core/commit_differ.py +599 -0
  29. intentumdiff/core/config.py +51 -0
  30. intentumdiff/core/cst_serializer.py +101 -0
  31. intentumdiff/core/diffignore.py +87 -0
  32. intentumdiff/core/index.py +189 -0
  33. intentumdiff/core/indexer.py +792 -0
  34. intentumdiff/core/models.py +837 -0
  35. intentumdiff/differ.py +2195 -0
  36. intentumdiff/github_app.py +287 -0
  37. intentumdiff/intentumdiff_rust_core/__init__.py +7 -0
  38. intentumdiff/intentumdiff_rust_core/ffi.py +8 -0
  39. intentumdiff/intentumdiff_rust_core/libintentumdiff_rust_core.so +0 -0
  40. intentumdiff/invariances/__init__.py +2 -0
  41. intentumdiff/invariances/rules.schema.json +283 -0
  42. intentumdiff/invariances/rules.yaml +349 -0
  43. intentumdiff/live_server.py +1314 -0
  44. intentumdiff/lsp/__init__.py +67 -0
  45. intentumdiff/lsp/client.py +544 -0
  46. intentumdiff/lsp/config.py +96 -0
  47. intentumdiff/lsp/enricher.py +227 -0
  48. intentumdiff/lsp/exceptions.py +27 -0
  49. intentumdiff/lsp/launcher.py +273 -0
  50. intentumdiff/lsp/servers.py +356 -0
  51. intentumdiff/lsp_server/__init__.py +14 -0
  52. intentumdiff/lsp_server/_codelens.py +67 -0
  53. intentumdiff/lsp_server/_diagnostics.py +62 -0
  54. intentumdiff/lsp_server/_handlers.py +175 -0
  55. intentumdiff/lsp_server/server.py +205 -0
  56. intentumdiff/plugins/__init__.py +1 -0
  57. intentumdiff/plugins/adapter.py +397 -0
  58. intentumdiff/plugins/builtins.py +323 -0
  59. intentumdiff/plugins/exceptions.py +93 -0
  60. intentumdiff/plugins/hub.py +1155 -0
  61. intentumdiff/plugins/language_metadata.py +250 -0
  62. intentumdiff/plugins/loader.py +1252 -0
  63. intentumdiff/plugins/registry.py +1079 -0
  64. intentumdiff/plugins/registry.schema.json +99 -0
  65. intentumdiff/plugins/registry_schema.py +280 -0
  66. intentumdiff/plugins/wit/plugin.wit +351 -0
  67. intentumdiff/rust_core.py +2370 -0
  68. intentumdiff/serve/__init__.py +19 -0
  69. intentumdiff/serve/_app.py +485 -0
  70. intentumdiff/serve/_static/index.html +326 -0
  71. intentumdiff/serve/_static/playground.js +567 -0
  72. intentumdiff/sources/__init__.py +1 -0
  73. intentumdiff/sources/base.py +28 -0
  74. intentumdiff/sources/file_source.py +48 -0
  75. intentumdiff/sources/git_source.py +375 -0
  76. intentumdiff/sources/live_buffer_source.py +113 -0
  77. intentumdiff/sources/patch_source.py +126 -0
  78. intentumdiff/sources/string_source.py +44 -0
  79. intentumdiff/testing.py +165 -0
  80. intentumdiff/vcs/__init__.py +37 -0
  81. intentumdiff/vcs/_safe_path.py +50 -0
  82. intentumdiff/vcs/base.py +136 -0
  83. intentumdiff/vcs/git_backend.py +97 -0
  84. intentumdiff/vcs/git_cli.py +100 -0
  85. intentumdiff/vcs/hg_backend.py +94 -0
  86. intentumdiff/vcs/perforce_backend.py +109 -0
  87. intentumdiff/vcs/svn_backend.py +105 -0
  88. intentumdiff/wasm/.gitkeep +2 -0
  89. intentumdiff/wasm/abap_parser.wasm +0 -0
  90. intentumdiff/wasm/adf_parser.wasm +0 -0
  91. intentumdiff/wasm/asciidoc_parser.wasm +0 -0
  92. intentumdiff/wasm/asm_parser.wasm +0 -0
  93. intentumdiff/wasm/assemblyscript_parser.wasm +0 -0
  94. intentumdiff/wasm/astro_parser.wasm +0 -0
  95. intentumdiff/wasm/bash_parser.wasm +0 -0
  96. intentumdiff/wasm/clojure_parser.wasm +0 -0
  97. intentumdiff/wasm/cmake_parser.wasm +0 -0
  98. intentumdiff/wasm/cpp_parser.wasm +0 -0
  99. intentumdiff/wasm/csharp_parser.wasm +0 -0
  100. intentumdiff/wasm/css_parser.wasm +0 -0
  101. intentumdiff/wasm/dart_parser.wasm +0 -0
  102. intentumdiff/wasm/databricks_parser.wasm +0 -0
  103. intentumdiff/wasm/dax_parser.wasm +0 -0
  104. intentumdiff/wasm/delphi_parser.wasm +0 -0
  105. intentumdiff/wasm/dockerfile_parser.wasm +0 -0
  106. intentumdiff/wasm/elixir_parser.wasm +0 -0
  107. intentumdiff/wasm/freebasic_parser.wasm +0 -0
  108. intentumdiff/wasm/generic_parser.wasm +0 -0
  109. intentumdiff/wasm/gitignore_parser.wasm +0 -0
  110. intentumdiff/wasm/go_parser.wasm +0 -0
  111. intentumdiff/wasm/gomod_parser.wasm +0 -0
  112. intentumdiff/wasm/graphql_parser.wasm +0 -0
  113. intentumdiff/wasm/groovy_parser.wasm +0 -0
  114. intentumdiff/wasm/haskell_parser.wasm +0 -0
  115. intentumdiff/wasm/html_parser.wasm +0 -0
  116. intentumdiff/wasm/ini_parser.wasm +0 -0
  117. intentumdiff/wasm/java_parser.wasm +0 -0
  118. intentumdiff/wasm/js_ts_parser.wasm +0 -0
  119. intentumdiff/wasm/json_parser.wasm +0 -0
  120. intentumdiff/wasm/kotlin_parser.wasm +0 -0
  121. intentumdiff/wasm/latex_parser.wasm +0 -0
  122. intentumdiff/wasm/lua_parser.wasm +0 -0
  123. intentumdiff/wasm/make_parser.wasm +0 -0
  124. intentumdiff/wasm/markdown_parser.wasm +0 -0
  125. intentumdiff/wasm/mdx_parser.wasm +0 -0
  126. intentumdiff/wasm/ocaml_parser.wasm +0 -0
  127. intentumdiff/wasm/odin_parser.wasm +0 -0
  128. intentumdiff/wasm/parser_manifest.json +590 -0
  129. intentumdiff/wasm/perl_parser.wasm +0 -0
  130. intentumdiff/wasm/php_parser.wasm +0 -0
  131. intentumdiff/wasm/plsql_parser.wasm +0 -0
  132. intentumdiff/wasm/po_parser.wasm +0 -0
  133. intentumdiff/wasm/postscript_parser.wasm +0 -0
  134. intentumdiff/wasm/powershell_parser.wasm +0 -0
  135. intentumdiff/wasm/proto_parser.wasm +0 -0
  136. intentumdiff/wasm/puppet_parser.wasm +0 -0
  137. intentumdiff/wasm/python_parser.wasm +0 -0
  138. intentumdiff/wasm/qsharp_parser.wasm +0 -0
  139. intentumdiff/wasm/r_parser.wasm +0 -0
  140. intentumdiff/wasm/reasonml_parser.wasm +0 -0
  141. intentumdiff/wasm/ruby_parser.wasm +0 -0
  142. intentumdiff/wasm/rust_parser.wasm +0 -0
  143. intentumdiff/wasm/sas_parser.wasm +0 -0
  144. intentumdiff/wasm/scala_parser.wasm +0 -0
  145. intentumdiff/wasm/scss_parser.wasm +0 -0
  146. intentumdiff/wasm/sql_parser.wasm +0 -0
  147. intentumdiff/wasm/squirrel_parser.wasm +0 -0
  148. intentumdiff/wasm/svelte_parser.wasm +0 -0
  149. intentumdiff/wasm/swift_parser.wasm +0 -0
  150. intentumdiff/wasm/terraform_parser.wasm +0 -0
  151. intentumdiff/wasm/toml_parser.wasm +0 -0
  152. intentumdiff/wasm/tsql_parser.wasm +0 -0
  153. intentumdiff/wasm/vbnet_parser.wasm +0 -0
  154. intentumdiff/wasm/vue_parser.wasm +0 -0
  155. intentumdiff/wasm/wat_parser.wasm +0 -0
  156. intentumdiff/wasm/xml_parser.wasm +0 -0
  157. intentumdiff/wasm/yaml_parser.wasm +0 -0
  158. intentumdiff/wasm/zig_parser.wasm +0 -0
  159. intentumdiff/watcher.py +259 -0
  160. intentumdiff_python-0.0.1.dist-info/METADATA +112 -0
  161. intentumdiff_python-0.0.1.dist-info/RECORD +165 -0
  162. intentumdiff_python-0.0.1.dist-info/WHEEL +4 -0
  163. intentumdiff_python-0.0.1.dist-info/entry_points.txt +80 -0
  164. intentumdiff_python-0.0.1.dist-info/licenses/LICENSE +21 -0
  165. intentumdiff_python-0.0.1.dist-info/sboms/intentumdiff-rust-core.cyclonedx.json +10968 -0
@@ -0,0 +1,356 @@
1
+ """
2
+ intentumdiff.lsp.servers
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Known language server specifications for auto-start support.
6
+
7
+ Each entry in :data:`KNOWN_SERVER_SPECS` describes how to launch the server
8
+ for a given language. Two transports are supported:
9
+
10
+ **tcp** — IntentumDiff connects to a loopback TCP socket. Manual
11
+ already-running TCP servers are supported. Auto-started TCP servers are
12
+ legacy-only and require an explicit trust opt-in because generic LSP servers
13
+ cannot prove post-bind child ownership.
14
+
15
+ **stdio** — the server is started with stdin/stdout pipes and the
16
+ :class:`~intentumdiff.lsp.client.AsyncLspClient` communicates directly
17
+ over those streams. No TCP socket is involved.
18
+
19
+ The command templates may contain ``{host}`` and ``{port}`` placeholders
20
+ (resolved at launch time by :class:`~intentumdiff.lsp.launcher.LspServerProcess`).
21
+
22
+ See https://langserver.org/ for the full directory of language server implementations.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import logging
29
+ from dataclasses import dataclass, field
30
+ from pathlib import Path
31
+ from typing import TYPE_CHECKING, Literal
32
+
33
+ from pydantic import BaseModel, Field, model_validator
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ if TYPE_CHECKING:
38
+ pass # kept for future annotations
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class LspServerSpec:
43
+ """Auto-start specification for a language server.
44
+
45
+ Attributes
46
+ ----------
47
+ command:
48
+ Executable and arguments. For TCP servers, ``{host}`` and ``{port}``
49
+ placeholders are substituted at launch time.
50
+ transport:
51
+ ``"tcp"`` — a separate process that listens on a TCP port.
52
+ ``"stdio"`` — a process that speaks LSP over stdin/stdout.
53
+ startup_timeout:
54
+ Seconds to wait for a TCP server to become reachable after being
55
+ spawned. Ignored for stdio servers.
56
+ install_hint:
57
+ Human-readable install command shown when the server binary is
58
+ not found.
59
+ allow_unverified_tcp_autostart:
60
+ Legacy escape hatch for TCP auto-start. Leave ``False`` unless the
61
+ operator explicitly trusts the command and accepts the local port-race
62
+ residual risk. Prefer stdio or manual already-running TCP instead.
63
+ """
64
+
65
+ command: tuple[str, ...]
66
+ transport: Literal["tcp", "stdio"] = "stdio"
67
+ startup_timeout: float = 15.0
68
+ install_hint: str = ""
69
+ allow_unverified_tcp_autostart: bool = False
70
+
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # Auto-start specs
74
+ # ---------------------------------------------------------------------------
75
+
76
+ KNOWN_SERVER_SPECS: dict[str, LspServerSpec] = {
77
+ # ── Stdio-preferred built-ins (intentumdiff owns the child pipes) ───────────────
78
+ "python": LspServerSpec(
79
+ command=("pylsp",),
80
+ transport="stdio",
81
+ startup_timeout=10.0,
82
+ install_hint="uv pip install python-lsp-server",
83
+ ),
84
+ "go": LspServerSpec(
85
+ command=("gopls",),
86
+ transport="stdio",
87
+ startup_timeout=20.0,
88
+ install_hint="go install golang.org/x/tools/gopls@latest",
89
+ ),
90
+ "ruby": LspServerSpec(
91
+ command=("solargraph", "stdio"),
92
+ transport="stdio",
93
+ startup_timeout=15.0,
94
+ install_hint="gem install solargraph",
95
+ ),
96
+ "php": LspServerSpec(
97
+ command=("phpactor", "language-server"),
98
+ transport="stdio",
99
+ startup_timeout=10.0,
100
+ install_hint="composer global require phpactor/phpactor",
101
+ ),
102
+
103
+ # ── Stdio-native (spawn with pipes; client owns the process) ────────────
104
+ "javascript": LspServerSpec(
105
+ command=("typescript-language-server", "--stdio"),
106
+ transport="stdio",
107
+ install_hint="npm install -g typescript-language-server typescript",
108
+ ),
109
+ "typescript": LspServerSpec(
110
+ command=("typescript-language-server", "--stdio"),
111
+ transport="stdio",
112
+ install_hint="npm install -g typescript-language-server typescript",
113
+ ),
114
+ "tsx": LspServerSpec(
115
+ command=("typescript-language-server", "--stdio"),
116
+ transport="stdio",
117
+ install_hint="npm install -g typescript-language-server typescript",
118
+ ),
119
+ "rust": LspServerSpec(
120
+ command=("rust-analyzer",),
121
+ transport="stdio",
122
+ install_hint="rustup component add rust-analyzer",
123
+ ),
124
+ "c": LspServerSpec(
125
+ command=("clangd",),
126
+ transport="stdio",
127
+ install_hint="https://clangd.llvm.org/installation",
128
+ ),
129
+ "cpp": LspServerSpec(
130
+ command=("clangd",),
131
+ transport="stdio",
132
+ install_hint="https://clangd.llvm.org/installation",
133
+ ),
134
+ "bash": LspServerSpec(
135
+ command=("bash-language-server", "start"),
136
+ transport="stdio",
137
+ install_hint="npm install -g bash-language-server",
138
+ ),
139
+ "kotlin": LspServerSpec(
140
+ command=("kotlin-language-server",),
141
+ transport="stdio",
142
+ install_hint="https://github.com/fwcd/kotlin-language-server/releases",
143
+ ),
144
+ "swift": LspServerSpec(
145
+ command=("sourcekit-lsp",),
146
+ transport="stdio",
147
+ install_hint="Included with Xcode or https://swift.org/download",
148
+ ),
149
+ "java": LspServerSpec(
150
+ command=("jdtls",),
151
+ transport="stdio",
152
+ install_hint="https://github.com/eclipse/eclipse.jdt.ls",
153
+ ),
154
+ "csharp": LspServerSpec(
155
+ command=("OmniSharp", "--languageserver"),
156
+ transport="stdio",
157
+ install_hint="https://github.com/OmniSharp/omnisharp-roslyn/releases",
158
+ ),
159
+
160
+ # ── dbt Fusion LSP (dbt-sql, dbt-yaml) ─────────────────────────────────
161
+ # dbt-lsp is the language server shipped alongside the dbt Fusion engine.
162
+ # It understands dbt-flavoured SQL and YAML, providing type information
163
+ # from compiled warehouse schemas. Install via the dbt VS Code extension
164
+ # (https://docs.getdbt.com/docs/install-dbt-extension) or directly:
165
+ # curl -fsSL https://public.cdn.getdbt.com/fs/install/install.sh \
166
+ # | sh -s -- --update --package dbt-lsp
167
+ "dbt-sql": LspServerSpec(
168
+ command=("dbt-lsp",),
169
+ transport="stdio",
170
+ install_hint="https://docs.getdbt.com/docs/install-dbt-extension",
171
+ ),
172
+ "dbt-yaml": LspServerSpec(
173
+ command=("dbt-lsp",),
174
+ transport="stdio",
175
+ install_hint="https://docs.getdbt.com/docs/install-dbt-extension",
176
+ ),
177
+ }
178
+
179
+ # ---------------------------------------------------------------------------
180
+ # Legacy compat: default host:port addresses for manual server connections
181
+ # ---------------------------------------------------------------------------
182
+
183
+ KNOWN_SERVERS: dict[str, str] = {
184
+ "python": "localhost:2087",
185
+ "javascript": "localhost:2088",
186
+ "typescript": "localhost:2088",
187
+ "tsx": "localhost:2088",
188
+ "rust": "localhost:2089",
189
+ "java": "localhost:2090",
190
+ "go": "localhost:2091",
191
+ "csharp": "localhost:2092",
192
+ "c": "localhost:2093",
193
+ "cpp": "localhost:2093",
194
+ "ruby": "localhost:2094",
195
+ "swift": "localhost:2095",
196
+ "kotlin": "localhost:2096",
197
+ "php": "localhost:2097",
198
+ "bash": "localhost:2098",
199
+ "dbt-sql": "localhost:2099",
200
+ "dbt-yaml": "localhost:2100",
201
+ }
202
+
203
+ # ---------------------------------------------------------------------------
204
+ # User-defined server config — loaded from lsp_servers.json
205
+ # ---------------------------------------------------------------------------
206
+
207
+ class LspServerEntry(BaseModel, frozen=True):
208
+ """One user-defined LSP server entry, as it appears in ``lsp_servers.json``.
209
+
210
+ Each entry in that file is keyed by an arbitrary server name (like MCP)
211
+ and **must** include a ``language`` field so IntentumDiff knows which
212
+ language it serves.
213
+
214
+ Example ``lsp_servers.json``::
215
+
216
+ {
217
+ "my-pylsp": {
218
+ "language": "python",
219
+ "transport": "stdio",
220
+ "command": ["pylsp"]
221
+ },
222
+ "tsserver": {
223
+ "language": "typescript",
224
+ "transport": "stdio",
225
+ "command": ["typescript-language-server", "--stdio"]
226
+ },
227
+ "running-gopls": {
228
+ "language": "go",
229
+ "transport": "tcp",
230
+ "host": "localhost",
231
+ "port": 2091
232
+ }
233
+ }
234
+
235
+ When ``transport`` is ``"tcp"`` and ``command`` is provided the server can
236
+ only be auto-started by :class:`~intentumdiff.lsp.launcher.LspServerProcess`
237
+ when ``allow_unverified_tcp_autostart`` is set to ``true``. This is a
238
+ legacy trust decision; prefer ``stdio``.
239
+ When ``transport`` is ``"tcp"`` and **no** command is given, the server is
240
+ treated as already-running and IntentumDiff simply connects to
241
+ ``host:port``.
242
+ """
243
+
244
+ language: str = Field(min_length=1, description="Language identifier (e.g. 'python').")
245
+ transport: Literal["tcp", "stdio"] = Field(default="stdio")
246
+ command: tuple[str, ...] = Field(
247
+ default=(),
248
+ description="Command to spawn the server. For tcp, may include {host}/{port} placeholders.",
249
+ )
250
+ host: str = Field(default="localhost", min_length=1)
251
+ port: int | None = Field(
252
+ default=None,
253
+ description="Static TCP port (manual-connect mode only).",
254
+ )
255
+ startup_timeout: float = Field(default=15.0, gt=0)
256
+ install_hint: str = ""
257
+ allow_unverified_tcp_autostart: bool = Field(
258
+ default=False,
259
+ description=(
260
+ "Legacy opt-in for auto-started TCP LSP commands. Prefer stdio or "
261
+ "manual TCP. When false, tcp+command entries fail closed before launch."
262
+ ),
263
+ )
264
+
265
+ @model_validator(mode="after")
266
+ def _validate(self) -> "LspServerEntry":
267
+ if self.transport == "stdio" and not self.command:
268
+ raise ValueError("command is required for stdio transport")
269
+ if self.transport == "tcp" and not self.command and self.port is None:
270
+ raise ValueError(
271
+ "For tcp without command (manual-connect mode) port is required"
272
+ )
273
+ if self.port is not None and not (1 <= self.port <= 65535):
274
+ raise ValueError("port must be between 1 and 65535")
275
+ return self
276
+
277
+ @property
278
+ def is_manual_connect(self) -> bool:
279
+ """``True`` when this is a pre-started server we just connect to.
280
+
281
+ This is the case for ``transport="tcp"`` entries that have **no**
282
+ ``command`` — just ``host`` and ``port``.
283
+ """
284
+ return self.transport == "tcp" and not self.command
285
+
286
+ def to_spec(self) -> LspServerSpec:
287
+ """Convert to an :class:`LspServerSpec` for auto-start use.
288
+
289
+ Only valid for entries that have a ``command`` (auto-start mode).
290
+ """
291
+ if not self.command:
292
+ raise ValueError(
293
+ "Cannot convert a manual-connect entry (no command) to LspServerSpec. "
294
+ "Use LspServerConfig.tcp(host, port=port) directly."
295
+ )
296
+ return LspServerSpec(
297
+ command=self.command,
298
+ transport=self.transport,
299
+ startup_timeout=self.startup_timeout,
300
+ install_hint=self.install_hint,
301
+ allow_unverified_tcp_autostart=self.allow_unverified_tcp_autostart,
302
+ )
303
+
304
+
305
+ def load_lsp_servers_json(path: "Path | str") -> dict[str, LspServerEntry]:
306
+ """Load user-defined LSP server entries from an ``lsp_servers.json`` file.
307
+
308
+ Returns a mapping of **language → entry**. If multiple entries share the
309
+ same language the last one in the file wins. Returns an empty dict if the
310
+ file does not exist.
311
+
312
+ Parameters
313
+ ----------
314
+ path:
315
+ Path to the ``lsp_servers.json`` file.
316
+
317
+ Raises
318
+ ------
319
+ ValueError
320
+ If the file is not valid JSON or any entry fails validation.
321
+ """
322
+ p = Path(path)
323
+ if not p.exists():
324
+ return {}
325
+
326
+ with p.open("r", encoding="utf-8") as fh:
327
+ try:
328
+ raw = json.load(fh)
329
+ except json.JSONDecodeError as exc:
330
+ raise ValueError(f"{p}: invalid JSON — {exc}") from exc
331
+
332
+ if not isinstance(raw, dict):
333
+ raise ValueError(f"{p}: expected a JSON object at the top level")
334
+
335
+ result: dict[str, LspServerEntry] = {}
336
+ for server_name, data in raw.items():
337
+ if not isinstance(data, dict):
338
+ raise ValueError(
339
+ f"{p}: entry {server_name!r} must be a JSON object"
340
+ )
341
+ try:
342
+ entry = LspServerEntry.model_validate(data)
343
+ except Exception as exc:
344
+ raise ValueError(
345
+ f"{p}: invalid entry {server_name!r}: {exc}"
346
+ ) from exc
347
+ # Key by language; first entry for a language wins.
348
+ if entry.language not in result:
349
+ result[entry.language] = entry
350
+ else:
351
+ logger.debug(
352
+ "lsp_servers.json: skipping %r — language %r already registered",
353
+ server_name, entry.language,
354
+ )
355
+
356
+ return result
@@ -0,0 +1,14 @@
1
+ """
2
+ intentumdiff.lsp_server
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ LSP server package — exposes :func:`create_server` for editor integrations.
6
+
7
+ Requires the ``lsp-server`` extra::
8
+
9
+ pip install "intentumdiff[lsp-server]"
10
+ """
11
+
12
+ from intentumdiff.lsp_server.server import create_server
13
+
14
+ __all__ = ["create_server"]
@@ -0,0 +1,67 @@
1
+ """
2
+ intentumdiff.lsp_server._codelens
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Translate a ``SemanticDiff`` into a list of LSP ``CodeLens`` objects.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from lsprotocol import types as lsp_types
11
+
12
+ from intentumdiff.core.models import Change, ChangeType, SemanticDiff, SemanticNode
13
+
14
+ # Change types that are surfaced as code lenses.
15
+ _CODELENS_CHANGE_TYPES: frozenset[str] = frozenset({
16
+ ChangeType.REFACTORING,
17
+ ChangeType.MOVE,
18
+ ChangeType.MOVE_TO_MODULE,
19
+ ChangeType.CROSS_FILE_RENAME,
20
+ ChangeType.REORDER,
21
+ })
22
+
23
+
24
+ def node_to_lsp_range(node: SemanticNode) -> lsp_types.Range:
25
+ """Convert a ``SemanticNode``'s position to an LSP ``Range`` (0-indexed)."""
26
+ pos = node.position
27
+ return lsp_types.Range(
28
+ start=lsp_types.Position(line=pos.start_line, character=pos.start_col),
29
+ end=lsp_types.Position(line=pos.end_line, character=pos.end_col),
30
+ )
31
+
32
+
33
+ def _codelens_title(change: Change) -> str:
34
+ """Build the display title for a code-lens entry."""
35
+ if change.refactoring_kind is not None:
36
+ return f"\u21bb {change.refactoring_kind.name}: {change.description}"
37
+ ct = change.change_type
38
+ name = ct.name if isinstance(ct, ChangeType) else str(ct)
39
+ return f"\u27f3 {name}: {change.description}"
40
+
41
+
42
+ def semantic_diff_to_codelens(diff: SemanticDiff) -> list[lsp_types.CodeLens]:
43
+ """Translate *diff* into a list of display-only LSP code lenses.
44
+
45
+ Emitted for changes whose ``change_type`` is in
46
+ ``{REFACTORING, MOVE, MOVE_TO_MODULE, CROSS_FILE_RENAME, REORDER}``.
47
+ The ``command`` field is left empty (display-only; no action on click).
48
+ """
49
+ lenses: list[lsp_types.CodeLens] = []
50
+
51
+ for change in diff.changes:
52
+ if change.change_type not in _CODELENS_CHANGE_TYPES:
53
+ continue
54
+ node = change.new_node or change.old_node
55
+ if node is None:
56
+ continue
57
+ lenses.append(
58
+ lsp_types.CodeLens(
59
+ range=node_to_lsp_range(node),
60
+ command=lsp_types.Command(
61
+ title=_codelens_title(change),
62
+ command="",
63
+ ),
64
+ )
65
+ )
66
+
67
+ return lenses
@@ -0,0 +1,62 @@
1
+ """
2
+ intentumdiff.lsp_server._diagnostics
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Translate a ``SemanticDiff`` into a list of LSP ``Diagnostic`` objects.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from lsprotocol import types as lsp_types
11
+
12
+ from intentumdiff.core.models import ChangeType, SemanticDiff, SemanticNode
13
+
14
+ # Sentinel range covering the whole document — used for parse-error diagnostics.
15
+ _FULL_DOC_RANGE = lsp_types.Range(
16
+ start=lsp_types.Position(line=0, character=0),
17
+ end=lsp_types.Position(line=2**31 - 1, character=0),
18
+ )
19
+
20
+
21
+ def node_to_lsp_range(node: SemanticNode) -> lsp_types.Range:
22
+ """Convert a ``SemanticNode``'s position to an LSP ``Range``.
23
+
24
+ ``NodePosition`` fields are already 0-indexed so no adjustment is needed.
25
+ """
26
+ pos = node.position
27
+ return lsp_types.Range(
28
+ start=lsp_types.Position(line=pos.start_line, character=pos.start_col),
29
+ end=lsp_types.Position(line=pos.end_line, character=pos.end_col),
30
+ )
31
+
32
+
33
+ def semantic_diff_to_diagnostics(diff: SemanticDiff) -> list[lsp_types.Diagnostic]:
34
+ """Translate *diff* into a list of LSP diagnostics.
35
+
36
+ * ``STYLE_ONLY`` changes → ``Hint`` severity (informational, on ``new_node``).
37
+ * Parse errors → ``Warning`` severity (full-document range).
38
+ """
39
+ diags: list[lsp_types.Diagnostic] = []
40
+
41
+ for change in diff.changes:
42
+ if change.change_type == ChangeType.STYLE_ONLY and change.new_node is not None:
43
+ diags.append(
44
+ lsp_types.Diagnostic(
45
+ range=node_to_lsp_range(change.new_node),
46
+ severity=lsp_types.DiagnosticSeverity.Hint,
47
+ message="Style-only change — no semantic impact",
48
+ source="intentumdiff",
49
+ )
50
+ )
51
+
52
+ for err in diff.parse_errors:
53
+ diags.append(
54
+ lsp_types.Diagnostic(
55
+ range=_FULL_DOC_RANGE,
56
+ severity=lsp_types.DiagnosticSeverity.Warning,
57
+ message=f"Parse error: {err}",
58
+ source="intentumdiff",
59
+ )
60
+ )
61
+
62
+ return diags
@@ -0,0 +1,175 @@
1
+ """
2
+ intentumdiff.lsp_server._handlers
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Server state dataclass and async diff-scheduling helpers used by
6
+ ``intentumdiff.lsp_server.server``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import logging
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+ from urllib.parse import unquote, urlparse
16
+
17
+ from intentumdiff.core.models import SemanticDiff
18
+ from intentumdiff.differ import SemanticDiffer
19
+
20
+ try:
21
+ from pygls.lsp.server import LanguageServer # pygls >= 2.x
22
+ except ImportError:
23
+ from pygls.server import LanguageServer # type: ignore[assignment] # pygls 1.x
24
+
25
+ log = logging.getLogger(__name__)
26
+
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Server state
30
+ # ---------------------------------------------------------------------------
31
+
32
+ @dataclass
33
+ class _ServerState:
34
+ """Mutable state shared across all feature handlers for a single server instance."""
35
+
36
+ differ: SemanticDiffer
37
+ ref: str
38
+ debounce: float
39
+ diff_cache: dict[str, SemanticDiff] = field(default_factory=dict)
40
+ pending_tasks: dict[str, asyncio.Task] = field(default_factory=dict)
41
+ supports_codelens_refresh: bool = False
42
+
43
+
44
+ # ---------------------------------------------------------------------------
45
+ # URI helpers
46
+ # ---------------------------------------------------------------------------
47
+
48
+ def uri_to_path(uri: str, workspace_root: Path | None = None) -> Path:
49
+ """Convert a ``file://`` URI to a :class:`~pathlib.Path`.
50
+
51
+ Raises :class:`ValueError` for non-file schemes, path-traversal attempts,
52
+ or when the resolved path escapes *workspace_root* (if provided).
53
+ """
54
+ parsed = urlparse(uri)
55
+ if parsed.scheme not in ("file", ""):
56
+ raise ValueError(f"Only file:// URIs are supported, got: {uri!r}")
57
+ path = Path(unquote(parsed.path))
58
+ # Reject explicit traversal components
59
+ if ".." in path.parts:
60
+ raise ValueError(f"Path traversal rejected in URI: {uri!r}")
61
+ # On Windows, urlparse puts a leading '/' before the drive letter —
62
+ # strip it so Path('C:/foo') is constructed correctly.
63
+ if path.parts and path.parts[0] in ("/", "\\") and len(path.parts) > 1:
64
+ # Join with "/" so we get an absolute path ("C:/Users/...") rather than
65
+ # a drive-relative one ("C:Users/...") which Path(*parts) would produce.
66
+ candidate = Path("/".join(path.parts[1:]))
67
+ if candidate.drive:
68
+ path = candidate
69
+ resolved = path.resolve()
70
+ if workspace_root is not None:
71
+ root_resolved = workspace_root.resolve()
72
+ try:
73
+ resolved.relative_to(root_resolved)
74
+ except ValueError:
75
+ raise ValueError(
76
+ f"URI {uri!r} resolves to {resolved!r} which is outside the "
77
+ f"workspace root {root_resolved!r}."
78
+ )
79
+ return resolved
80
+
81
+
82
+ # ---------------------------------------------------------------------------
83
+ # Async diff scheduling
84
+ # ---------------------------------------------------------------------------
85
+
86
+ async def schedule_diff(
87
+ server, # LanguageServer — avoid circular import at module level
88
+ state: _ServerState,
89
+ uri: str,
90
+ content: str,
91
+ ) -> None:
92
+ """Cancel any in-flight diff for *uri* and schedule a fresh one."""
93
+ existing = state.pending_tasks.get(uri)
94
+ if existing is not None and not existing.done():
95
+ existing.cancel()
96
+
97
+ task = asyncio.create_task(_compute_and_push(server, state, uri, content))
98
+ state.pending_tasks[uri] = task
99
+
100
+
101
+ async def _compute_and_push(
102
+ server,
103
+ state: _ServerState,
104
+ uri: str,
105
+ content: str,
106
+ ) -> None:
107
+ """Debounce, compute diff in a thread-pool, then push results to the client."""
108
+ try:
109
+ await asyncio.sleep(state.debounce)
110
+
111
+ loop = asyncio.get_running_loop()
112
+ diff = await loop.run_in_executor(
113
+ None, _do_diff, state, server, uri, content
114
+ )
115
+ if diff is None:
116
+ return
117
+
118
+ state.diff_cache[uri] = diff
119
+
120
+ # Publish diagnostics (push model — no client request needed).
121
+ from intentumdiff.lsp_server._diagnostics import semantic_diff_to_diagnostics
122
+
123
+ diags = semantic_diff_to_diagnostics(diff)
124
+ server.publish_diagnostics(uri, diags)
125
+
126
+ # Ask the client to refresh code-lens decorations when supported.
127
+ if state.supports_codelens_refresh:
128
+ try:
129
+ server.lsp.send_request(
130
+ "workspace/codeLens/refresh",
131
+ None,
132
+ )
133
+ except Exception: # noqa: BLE001
134
+ log.debug("intentumdiff: code lens refresh request failed", exc_info=True)
135
+
136
+ except asyncio.CancelledError:
137
+ raise # propagate cancellation — do not swallow
138
+ except Exception as exc: # noqa: BLE001
139
+ log.warning("intentumdiff: unhandled error during diff for %s: %s", uri, exc)
140
+
141
+
142
+ # ---------------------------------------------------------------------------
143
+ # Blocking diff computation (runs in thread-pool executor)
144
+ # ---------------------------------------------------------------------------
145
+
146
+ def _do_diff(
147
+ state: _ServerState,
148
+ server,
149
+ uri: str,
150
+ content: str,
151
+ ) -> SemanticDiff | None:
152
+ """Compute a ``SemanticDiff`` synchronously.
153
+
154
+ Intended to be called via ``loop.run_in_executor`` so the event loop is
155
+ never blocked by parser/wasm work.
156
+ """
157
+ try:
158
+ root_uri: str | None = getattr(server.workspace, "root_uri", None)
159
+ repo_root = uri_to_path(root_uri) if root_uri else Path.cwd()
160
+ file_path = uri_to_path(uri)
161
+ rel_path = file_path.relative_to(repo_root)
162
+
163
+ from intentumdiff.sources.live_buffer_source import LiveBufferSource
164
+
165
+ source = LiveBufferSource(
166
+ repo_path=repo_root,
167
+ file_path=str(rel_path),
168
+ live_content=content,
169
+ ref=state.ref,
170
+ )
171
+ return state.differ.diff(source)
172
+
173
+ except Exception as exc: # noqa: BLE001
174
+ log.warning("intentumdiff: diff failed for %s: %s", uri, exc)
175
+ return None