intentumdiff-python 0.0.1__py3-none-win_amd64.whl → 0.0.3b1__py3-none-win_amd64.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 (150) hide show
  1. intentumdiff/__init__.py +9 -0
  2. intentumdiff/__main__.py +12 -0
  3. intentumdiff/_differ_gate.py +0 -136
  4. intentumdiff/_differ_presentation.py +17 -735
  5. intentumdiff/_differ_runtime.py +13 -64
  6. intentumdiff/analysis/compile_commands.py +26 -141
  7. intentumdiff/analysis/cross_file.py +23 -25
  8. intentumdiff/analysis/diagnostics.py +1 -164
  9. intentumdiff/analysis/guardrail_reports.py +31 -33
  10. intentumdiff/analysis/guardrails.py +111 -188
  11. intentumdiff/analysis/schema_resolver.py +72 -360
  12. intentumdiff/analysis/user_schemas.py +57 -254
  13. intentumdiff/api.py +21 -0
  14. intentumdiff/cache/sqlite_store.py +5 -23
  15. intentumdiff/cli/__init__.py +59 -0
  16. intentumdiff/cli/_commands.py +243 -137
  17. intentumdiff/cli/_parser.py +51 -56
  18. intentumdiff/cli/_shared.py +151 -116
  19. intentumdiff/content_type.py +13 -30
  20. intentumdiff/core/commit_differ.py +137 -286
  21. intentumdiff/core/diffignore.py +28 -34
  22. intentumdiff/core/index.py +16 -18
  23. intentumdiff/core/indexer.py +148 -169
  24. intentumdiff/core/models.py +279 -83
  25. intentumdiff/differ.py +366 -1000
  26. intentumdiff/github_app.py +40 -27
  27. intentumdiff/intentumdiff_rust_core/intentumdiff_rust_core.dll +0 -0
  28. intentumdiff/live_server.py +197 -34
  29. intentumdiff/lsp/client.py +49 -43
  30. intentumdiff/lsp/enricher.py +19 -119
  31. intentumdiff/lsp/exceptions.py +6 -7
  32. intentumdiff/lsp/servers.py +10 -11
  33. intentumdiff/lsp_server/_codelens.py +24 -57
  34. intentumdiff/lsp_server/_diagnostics.py +23 -51
  35. intentumdiff/lsp_server/_handlers.py +67 -9
  36. intentumdiff/lsp_server/server.py +28 -8
  37. intentumdiff/plugins/adapter.py +5 -0
  38. intentumdiff/plugins/builtins.py +7 -14
  39. intentumdiff/plugins/exceptions.py +28 -0
  40. intentumdiff/plugins/hub.py +39 -43
  41. intentumdiff/plugins/loader.py +229 -215
  42. intentumdiff/plugins/registry.py +259 -207
  43. intentumdiff/plugins/registry.schema.json +156 -15
  44. intentumdiff/plugins/registry_schema.py +47 -140
  45. intentumdiff/rust_core.py +623 -1326
  46. intentumdiff/serve/_app.py +26 -35
  47. intentumdiff/sources/base.py +24 -0
  48. intentumdiff/sources/file_source.py +15 -2
  49. intentumdiff/sources/git_source.py +64 -185
  50. intentumdiff/sources/live_buffer_source.py +45 -5
  51. intentumdiff/sources/patch_source.py +36 -109
  52. intentumdiff/vcs/_safe_path.py +7 -0
  53. intentumdiff/vcs/base.py +6 -0
  54. intentumdiff/vcs/git_backend.py +1 -1
  55. intentumdiff/vcs/git_cli.py +0 -27
  56. intentumdiff/vcs/hg_backend.py +1 -1
  57. intentumdiff/vcs/perforce_backend.py +7 -1
  58. intentumdiff/vcs/svn_backend.py +1 -1
  59. intentumdiff/wasm/abap_parser.wasm +0 -0
  60. intentumdiff/wasm/adf_parser.wasm +0 -0
  61. intentumdiff/wasm/asciidoc_parser.wasm +0 -0
  62. intentumdiff/wasm/asm_parser.wasm +0 -0
  63. intentumdiff/wasm/assemblyscript_parser.wasm +0 -0
  64. intentumdiff/wasm/astro_parser.wasm +0 -0
  65. intentumdiff/wasm/bash_parser.wasm +0 -0
  66. intentumdiff/wasm/clojure_parser.wasm +0 -0
  67. intentumdiff/wasm/cmake_parser.wasm +0 -0
  68. intentumdiff/wasm/cpp_parser.wasm +0 -0
  69. intentumdiff/wasm/csharp_parser.wasm +0 -0
  70. intentumdiff/wasm/css_parser.wasm +0 -0
  71. intentumdiff/wasm/dart_parser.wasm +0 -0
  72. intentumdiff/wasm/databricks_parser.wasm +0 -0
  73. intentumdiff/wasm/dax_parser.wasm +0 -0
  74. intentumdiff/wasm/delphi_parser.wasm +0 -0
  75. intentumdiff/wasm/dockerfile_parser.wasm +0 -0
  76. intentumdiff/wasm/elixir_parser.wasm +0 -0
  77. intentumdiff/wasm/freebasic_parser.wasm +0 -0
  78. intentumdiff/wasm/generic_parser.wasm +0 -0
  79. intentumdiff/wasm/gitignore_parser.wasm +0 -0
  80. intentumdiff/wasm/go_parser.wasm +0 -0
  81. intentumdiff/wasm/gomod_parser.wasm +0 -0
  82. intentumdiff/wasm/graphql_parser.wasm +0 -0
  83. intentumdiff/wasm/groovy_parser.wasm +0 -0
  84. intentumdiff/wasm/haskell_parser.wasm +0 -0
  85. intentumdiff/wasm/html_parser.wasm +0 -0
  86. intentumdiff/wasm/html_renderer.wasm +0 -0
  87. intentumdiff/wasm/ini_parser.wasm +0 -0
  88. intentumdiff/wasm/java_parser.wasm +0 -0
  89. intentumdiff/wasm/js_ts_parser.wasm +0 -0
  90. intentumdiff/wasm/json_parser.wasm +0 -0
  91. intentumdiff/wasm/kotlin_parser.wasm +0 -0
  92. intentumdiff/wasm/latex_parser.wasm +0 -0
  93. intentumdiff/wasm/llm_renderer.wasm +0 -0
  94. intentumdiff/wasm/lua_parser.wasm +0 -0
  95. intentumdiff/wasm/make_parser.wasm +0 -0
  96. intentumdiff/wasm/markdown_parser.wasm +0 -0
  97. intentumdiff/wasm/mdx_parser.wasm +0 -0
  98. intentumdiff/wasm/ocaml_parser.wasm +0 -0
  99. intentumdiff/wasm/odin_parser.wasm +0 -0
  100. intentumdiff/wasm/parser_manifest.json +81 -2
  101. intentumdiff/wasm/patch_renderer.wasm +0 -0
  102. intentumdiff/wasm/perl_parser.wasm +0 -0
  103. intentumdiff/wasm/php_parser.wasm +0 -0
  104. intentumdiff/wasm/plsql_parser.wasm +0 -0
  105. intentumdiff/wasm/po_parser.wasm +0 -0
  106. intentumdiff/wasm/postscript_parser.wasm +0 -0
  107. intentumdiff/wasm/powershell_parser.wasm +0 -0
  108. intentumdiff/wasm/proto_parser.wasm +0 -0
  109. intentumdiff/wasm/puppet_parser.wasm +0 -0
  110. intentumdiff/wasm/python_parser.wasm +0 -0
  111. intentumdiff/wasm/qsharp_parser.wasm +0 -0
  112. intentumdiff/wasm/r_parser.wasm +0 -0
  113. intentumdiff/wasm/reasonml_parser.wasm +0 -0
  114. intentumdiff/wasm/ruby_parser.wasm +0 -0
  115. intentumdiff/wasm/rust_parser.wasm +0 -0
  116. intentumdiff/wasm/sas_parser.wasm +0 -0
  117. intentumdiff/wasm/scala_parser.wasm +0 -0
  118. intentumdiff/wasm/scss_parser.wasm +0 -0
  119. intentumdiff/wasm/sql_parser.wasm +0 -0
  120. intentumdiff/wasm/squirrel_parser.wasm +0 -0
  121. intentumdiff/wasm/svelte_parser.wasm +0 -0
  122. intentumdiff/wasm/swift_parser.wasm +0 -0
  123. intentumdiff/wasm/terminal_renderer.wasm +0 -0
  124. intentumdiff/wasm/terraform_parser.wasm +0 -0
  125. intentumdiff/wasm/toml_parser.wasm +0 -0
  126. intentumdiff/wasm/tsql_parser.wasm +0 -0
  127. intentumdiff/wasm/vbnet_parser.wasm +0 -0
  128. intentumdiff/wasm/vue_parser.wasm +0 -0
  129. intentumdiff/wasm/wasm_provenance.json +884 -0
  130. intentumdiff/wasm/wat_parser.wasm +0 -0
  131. intentumdiff/wasm/xml_parser.wasm +0 -0
  132. intentumdiff/wasm/yaml_parser.wasm +0 -0
  133. intentumdiff/wasm/zig_parser.wasm +0 -0
  134. intentumdiff/watcher.py +15 -17
  135. intentumdiff_python-0.0.3b1.dist-info/METADATA +188 -0
  136. intentumdiff_python-0.0.3b1.dist-info/RECORD +164 -0
  137. {intentumdiff_python-0.0.1.dist-info → intentumdiff_python-0.0.3b1.dist-info}/WHEEL +1 -1
  138. {intentumdiff_python-0.0.1.dist-info → intentumdiff_python-0.0.3b1.dist-info}/sboms/intentumdiff-rust-core.cyclonedx.json +905 -379
  139. intentumdiff/analysis/invariances.py +0 -1207
  140. intentumdiff/analysis/keyed_profiles.py +0 -25
  141. intentumdiff/analysis/resource_profiles.py +0 -14
  142. intentumdiff/analysis/text_review.py +0 -46
  143. intentumdiff/core/cst_serializer.py +0 -101
  144. intentumdiff/invariances/__init__.py +0 -2
  145. intentumdiff/invariances/rules.schema.json +0 -283
  146. intentumdiff/invariances/rules.yaml +0 -349
  147. intentumdiff_python-0.0.1.dist-info/METADATA +0 -112
  148. intentumdiff_python-0.0.1.dist-info/RECORD +0 -165
  149. {intentumdiff_python-0.0.1.dist-info → intentumdiff_python-0.0.3b1.dist-info}/entry_points.txt +0 -0
  150. {intentumdiff_python-0.0.1.dist-info → intentumdiff_python-0.0.3b1.dist-info}/licenses/LICENSE +0 -0
@@ -13,16 +13,14 @@ Usage
13
13
  type_map = await enricher.enrich(uri, source_text, root_node)
14
14
  # type_map: dict[node_id, type_string]
15
15
 
16
- The enricher only queries leaf nodes whose ``node_type`` is in
17
- ``_NAME_TYPES`` (identifiers, names, symbols …). It uses
16
+ The Rust engine selects hover targets and result node IDs. This adapter uses
18
17
  ``asyncio.gather`` to parallelise all hover requests for a single file,
19
18
  which keeps latency proportional to the server's response time rather than
20
19
  the number of nodes.
21
20
 
22
- LSP failures are non-fatal:
23
- - ``LspConnectionError`` — logged as a warning; an empty dict is returned.
24
- - ``LspTimeoutError`` per node — that node is silently skipped.
25
- - Any other exception — logged as a debug message; the node is skipped.
21
+ LSP transport failures fail closed: connection errors and hover timeouts are
22
+ reported to the indexer instead of being converted into an empty type map.
23
+ A successful hover response with no type remains a legitimate None result.
26
24
  """
27
25
 
28
26
  from __future__ import annotations
@@ -32,49 +30,10 @@ import logging
32
30
  import pathlib
33
31
 
34
32
  from intentumdiff.lsp.client import AsyncLspClient
35
- from intentumdiff.lsp.exceptions import LspConnectionError, LspTimeoutError
36
33
  from intentumdiff.core.models import SemanticNode
37
34
 
38
35
  logger = logging.getLogger(__name__)
39
36
 
40
- # Node types whose *own* position is hovered and whose *own* id gets the result.
41
- # Kept narrow: only specific name nodes the refactoring rules sub-classify.
42
- # Generic ``identifier``/``name``/``symbol`` are excluded — they appear
43
- # hundreds of times per file but are never directly read for ``type_info`` by
44
- # any refactoring rule.
45
- _NAME_TYPES = frozenset(
46
- {
47
- "function_name",
48
- "class_name",
49
- "variable_name",
50
- "method_name", # some parsers emit method_name instead of function_name
51
- }
52
- )
53
-
54
- # Declaration/parameter node types whose ``type_info`` is read by refactoring
55
- # rules (EXTRACT_VARIABLE, INTRODUCE_PARAMETER_OBJECT). The enricher hovers
56
- # at the *first name-leaf child's* position but stores the result under the
57
- # *declaration node's* id so it lands on the node the rules inspect.
58
- _DECL_NODE_TYPES = frozenset(
59
- {
60
- "assignment",
61
- "variable_declaration",
62
- "let_declaration",
63
- "const_declaration",
64
- "local_variable_declaration",
65
- "variable_declarator",
66
- }
67
- )
68
- _PARAM_NODE_TYPES = frozenset(
69
- {
70
- "parameter",
71
- "typed_parameter",
72
- "typed_identifier",
73
- "required_parameter",
74
- "optional_parameter",
75
- }
76
- )
77
-
78
37
  # Maximum concurrent hover requests per file. Most servers handle far more,
79
38
  # but we cap to avoid overwhelming a slow server.
80
39
  _MAX_CONCURRENT = 50
@@ -111,17 +70,13 @@ class TypeEnricher:
111
70
  Sends ``textDocument/didOpen``, fires all hover requests concurrently,
112
71
  then sends ``textDocument/didClose``.
113
72
 
114
- Returns an empty dict on connection failure so that the caller can
115
- continue the diff pipeline without type information.
73
+ Raises transport errors; only a completed query with no type results
74
+ produces an empty dict.
116
75
  """
117
76
  uri = _path_to_uri(file_path)
77
+ await self._client.did_open(uri, self._language, source_text)
118
78
  try:
119
- await self._client.did_open(uri, self._language, source_text)
120
- except LspConnectionError as exc:
121
- logger.warning("LSP type enrichment skipped (%s): %s", file_path, exc)
122
- return {}
123
- try:
124
- result = await self._query_all(uri, root)
79
+ result = await self._query_all(uri, root, source_text)
125
80
  finally:
126
81
  try:
127
82
  await self._client.did_close(uri)
@@ -131,62 +86,10 @@ class TypeEnricher:
131
86
 
132
87
  # ── Internal ──────────────────────────────────────────────────────────────
133
88
 
134
- def _first_name_leaf(self, node: SemanticNode) -> SemanticNode | None:
135
- """Return the first leaf descendant whose node_type is a name type."""
136
- all_name_types = _NAME_TYPES | frozenset({"identifier", "name", "symbol"})
137
- for child in node.children:
138
- if child.is_leaf() and child.node_type in all_name_types:
139
- return child
140
- found = self._first_name_leaf(child)
141
- if found is not None:
142
- return found
143
- return None
144
-
145
- def _collect_hover_targets(
146
- self, root: SemanticNode
147
- ) -> list[tuple[SemanticNode, SemanticNode]]:
148
- """Return ``(result_node, position_node)`` pairs to hover.
149
-
150
- * For **name-type leaves** (:data:`_NAME_TYPES`): hover at the leaf
151
- position, store result under the leaf's id.
152
- * For **declaration/parameter nodes** (:data:`_DECL_NODE_TYPES`,
153
- :data:`_PARAM_NODE_TYPES`): hover at the first name-leaf child's
154
- position, but store the result under the *declaration node's* id.
155
- This makes ``type_info`` land on the node that refactoring rules
156
- actually inspect (e.g. the ``assignment`` node for
157
- EXTRACT_VARIABLE).
158
-
159
- Result node ids are deduplicated so each node is queried at most once.
160
- """
161
- seen: set[str] = set()
162
- targets: list[tuple[SemanticNode, SemanticNode]] = []
163
-
164
- for node in [root, *root.descendants()]:
165
- if node.id in seen:
166
- continue
167
- if node.node_type in _NAME_TYPES and node.is_leaf():
168
- seen.add(node.id)
169
- targets.append((node, node))
170
- elif node.node_type in (_DECL_NODE_TYPES | _PARAM_NODE_TYPES):
171
- leaf = self._first_name_leaf(node)
172
- if leaf is not None:
173
- seen.add(node.id)
174
- targets.append((node, leaf))
175
-
176
- return targets
177
-
178
- def _hover_triples(self, root: SemanticNode) -> list[tuple[str, int, int]]:
179
- """``(result_node_id, line, col)`` hover targets — Rust core first (issue 100 S2),
180
- with :meth:`_collect_hover_targets` as the Python fallback/oracle."""
181
- from intentumdiff.rust_core import try_rust_collect_hover_targets
182
-
183
- rust_triples = try_rust_collect_hover_targets(root)
184
- if rust_triples is not None:
185
- return rust_triples
186
- return [
187
- (rn.id, pn.position.start_line, pn.position.start_col)
188
- for rn, pn in self._collect_hover_targets(root)
189
- ]
89
+ def _hover_triples(self, root: SemanticNode, source_text: str) -> list[tuple[str, int, int]]:
90
+ """Return the Rust engine's target decisions; failures propagate."""
91
+ from intentumdiff.rust_core import collect_lsp_hover_targets
92
+ return collect_lsp_hover_targets(root, source_text)
190
93
 
191
94
  async def _query_node(
192
95
  self,
@@ -200,23 +103,20 @@ class TypeEnricher:
200
103
  async with sem:
201
104
  try:
202
105
  type_str = await self._client.hover(uri, line, col)
203
- return node_id, type_str
204
- except LspTimeoutError:
205
- return node_id, None
206
- except Exception as exc:
207
- logger.debug(
208
- "LSP hover failed for node %s at %d:%d — %s",
209
- node_id, line, col, exc,
210
- )
211
- return node_id, None
106
+ except Exception as exc: # noqa: BLE001
107
+ raise RuntimeError(
108
+ f"LSP hover failed for node {node_id} at {line}:{col}: {exc}"
109
+ ) from exc
110
+ return node_id, type_str
212
111
 
213
112
  async def _query_all(
214
113
  self,
215
114
  uri: str,
216
115
  root: SemanticNode,
116
+ source_text: str,
217
117
  ) -> dict[str, str]:
218
118
  """Fire all hover requests concurrently; collect non-None results."""
219
- targets = self._hover_triples(root)
119
+ targets = self._hover_triples(root, source_text)
220
120
  if not targets:
221
121
  return {}
222
122
 
@@ -2,12 +2,11 @@
2
2
  intentumdiff.lsp.exceptions
3
3
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
4
 
5
- Non-fatal LSP warning exceptions.
5
+ LSP transport exceptions used to report failures through the public indexer.
6
6
 
7
- Both subclass ``Exception`` directly rather than a library-wide base so that
8
- callers can catch them without importing any other IntentumDiff symbol.
9
- They are treated as warnings in the pipeline — a file whose LSP enrichment
10
- fails is diffed without type information rather than aborting.
7
+ Both subclass ``Exception`` directly so callers can distinguish connection
8
+ failures and timeouts. A requested type-enrichment failure must not be
9
+ reported as a successfully completed bare semantic index.
11
10
  """
12
11
 
13
12
  from __future__ import annotations
@@ -16,12 +15,12 @@ from __future__ import annotations
16
15
  class LspConnectionError(Exception):
17
16
  """Raised when the TCP connection to the LSP server cannot be established.
18
17
 
19
- This is non-fatal: the diff pipeline continues without type enrichment.
18
+ Type enrichment cannot certify the file while connection is unavailable.
20
19
  """
21
20
 
22
21
 
23
22
  class LspTimeoutError(Exception):
24
23
  """Raised when an LSP request does not receive a response within the timeout.
25
24
 
26
- This is non-fatal: the affected node is left with ``type_info=None``.
25
+ The failing hover request is not silently treated as unknown type.
27
26
  """
@@ -26,7 +26,7 @@ from __future__ import annotations
26
26
 
27
27
  import json
28
28
  import logging
29
- from dataclasses import dataclass, field
29
+ from dataclasses import dataclass
30
30
  from pathlib import Path
31
31
  from typing import TYPE_CHECKING, Literal
32
32
 
@@ -305,9 +305,9 @@ treated as already-running and IntentumDiff simply connects to
305
305
  def load_lsp_servers_json(path: "Path | str") -> dict[str, LspServerEntry]:
306
306
  """Load user-defined LSP server entries from an ``lsp_servers.json`` file.
307
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.
308
+ Returns a mapping of **language → entry** in file order. Two entries for the
309
+ same language are rejected (ValueError naming both) rather than one silently
310
+ shadowing the other (#312). Returns an empty dict if the file does not exist.
311
311
 
312
312
  Parameters
313
313
  ----------
@@ -333,6 +333,7 @@ def load_lsp_servers_json(path: "Path | str") -> dict[str, LspServerEntry]:
333
333
  raise ValueError(f"{p}: expected a JSON object at the top level")
334
334
 
335
335
  result: dict[str, LspServerEntry] = {}
336
+ names: dict[str, str] = {}
336
337
  for server_name, data in raw.items():
337
338
  if not isinstance(data, dict):
338
339
  raise ValueError(
@@ -344,13 +345,11 @@ def load_lsp_servers_json(path: "Path | str") -> dict[str, LspServerEntry]:
344
345
  raise ValueError(
345
346
  f"{p}: invalid entry {server_name!r}: {exc}"
346
347
  ) 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,
348
+ if entry.language in result:
349
+ raise ValueError(
350
+ f"{p}: entries {server_name!r} and {names[entry.language]!r} both serve "
351
+ f"language {entry.language!r}; keep one"
354
352
  )
353
+ result[entry.language], names[entry.language] = entry, server_name
355
354
 
356
355
  return result
@@ -1,67 +1,34 @@
1
- """
2
- intentumdiff.lsp_server._codelens
3
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1
+ """Rust-owned LSP CodeLens presentation, with correct source-side UTF-16 spans.
4
2
 
5
- Translate a ``SemanticDiff`` into a list of LSP ``CodeLens`` objects.
3
+ Rust owns which changes become lenses, their titles, and byte→UTF-16
4
+ coordinates. This thin Python module only converts Rust JSON to lsprotocol DTOs.
6
5
  """
7
-
8
6
  from __future__ import annotations
9
7
 
10
8
  from lsprotocol import types as lsp_types
9
+ from lsprotocol.converters import get_converter
11
10
 
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}"
11
+ from intentumdiff.core.models import SemanticDiff, SemanticNode
12
+ from intentumdiff.rust_core import _c_abi_call
40
13
 
41
14
 
42
- def semantic_diff_to_codelens(diff: SemanticDiff) -> list[lsp_types.CodeLens]:
43
- """Translate *diff* into a list of display-only LSP code lenses.
15
+ def node_to_lsp_range(node: SemanticNode, source: str) -> lsp_types.Range:
16
+ """Convert only through the source-aware Rust C ABI, never guess columns."""
17
+ value = _c_abi_call("lsp_utf16_range", node.model_dump_json(), source)
18
+ if not isinstance(value, dict):
19
+ raise ValueError("Rust LSP range must be an object")
20
+ return get_converter().structure(value, lsp_types.Range)
44
21
 
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
22
 
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
23
+ def semantic_diff_to_codelens(
24
+ diff: SemanticDiff, *, old_source: str, new_source: str,
25
+ ) -> list[lsp_types.CodeLens]:
26
+ """Decode Rust's source-anchored CodeLens inventory without Python policy."""
27
+ value = _c_abi_call(
28
+ "lsp_server_codelens_utf16", diff.model_dump_json(),
29
+ old_source, new_source,
30
+ )
31
+ if not isinstance(value, list):
32
+ raise ValueError("Rust LSP CodeLens must be an array")
33
+ converter = get_converter()
34
+ return [converter.structure(row, lsp_types.CodeLens) for row in value]
@@ -1,62 +1,34 @@
1
- """
2
- intentumdiff.lsp_server._diagnostics
3
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1
+ """Rust-owned LSP diagnostics output, structured into Python transport DTOs.
4
2
 
5
- Translate a ``SemanticDiff`` into a list of LSP ``Diagnostic`` objects.
3
+ Semantic classification and UTF-8 byte→UTF-16 ranges belong to the Rust core.
4
+ The source-aware C ABI refuses invalid spans rather than publishing displaced
5
+ editor annotations. Python performs no diagnostic semantic classification.
6
6
  """
7
-
8
7
  from __future__ import annotations
9
8
 
10
9
  from lsprotocol import types as lsp_types
10
+ from lsprotocol.converters import get_converter
11
11
 
12
- from intentumdiff.core.models import ChangeType, SemanticDiff, SemanticNode
12
+ from intentumdiff.core.models import SemanticDiff, SemanticNode
13
+ from intentumdiff.rust_core import _c_abi_call
13
14
 
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
15
 
16
+ def node_to_lsp_range(node: SemanticNode, source: str) -> lsp_types.Range:
17
+ """Marshal a Rust source-judged UTF-16 range, requiring the actual source."""
18
+ value = _c_abi_call("lsp_utf16_range", node.model_dump_json(), source)
19
+ if not isinstance(value, dict):
20
+ raise ValueError("Rust LSP range must be an object")
21
+ return get_converter().structure(value, lsp_types.Range)
20
22
 
21
- def node_to_lsp_range(node: SemanticNode) -> lsp_types.Range:
22
- """Convert a ``SemanticNode``'s position to an LSP ``Range``.
23
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),
24
+ def semantic_diff_to_diagnostics(
25
+ diff: SemanticDiff, *, new_source: str,
26
+ ) -> list[lsp_types.Diagnostic]:
27
+ """Decode Rust's source-aware diagnostic inventory (no Python fallback)."""
28
+ value = _c_abi_call(
29
+ "lsp_server_diagnostics_utf16", diff.model_dump_json(), new_source,
30
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
31
+ if not isinstance(value, list):
32
+ raise ValueError("Rust LSP diagnostics must be an array")
33
+ converter = get_converter()
34
+ return [converter.structure(row, lsp_types.Diagnostic) for row in value]
@@ -20,7 +20,7 @@ from intentumdiff.differ import SemanticDiffer
20
20
  try:
21
21
  from pygls.lsp.server import LanguageServer # pygls >= 2.x
22
22
  except ImportError:
23
- from pygls.server import LanguageServer # type: ignore[assignment] # pygls 1.x
23
+ pass # type: ignore[assignment] # pygls 1.x
24
24
 
25
25
  log = logging.getLogger(__name__)
26
26
 
@@ -37,6 +37,7 @@ class _ServerState:
37
37
  ref: str
38
38
  debounce: float
39
39
  diff_cache: dict[str, SemanticDiff] = field(default_factory=dict)
40
+ source_cache: dict[str, tuple[str, str]] = field(default_factory=dict)
40
41
  pending_tasks: dict[str, asyncio.Task] = field(default_factory=dict)
41
42
  supports_codelens_refresh: bool = False
42
43
 
@@ -45,6 +46,17 @@ class _ServerState:
45
46
  # URI helpers
46
47
  # ---------------------------------------------------------------------------
47
48
 
49
+ class WorkspaceContainmentError(ValueError):
50
+ """A URI resolved outside the workspace root, or used explicit traversal.
51
+
52
+ A distinct type because this is a REFUSAL, not a fault: the server did its job. Logged and
53
+ reported separately from internal errors so an operator can tell "someone asked for a path
54
+ outside the workspace and we blocked it" from "the diff engine threw".
55
+
56
+ Subclasses ValueError deliberately - callers that already catch ValueError keep working.
57
+ """
58
+
59
+
48
60
  def uri_to_path(uri: str, workspace_root: Path | None = None) -> Path:
49
61
  """Convert a ``file://`` URI to a :class:`~pathlib.Path`.
50
62
 
@@ -57,7 +69,7 @@ def uri_to_path(uri: str, workspace_root: Path | None = None) -> Path:
57
69
  path = Path(unquote(parsed.path))
58
70
  # Reject explicit traversal components
59
71
  if ".." in path.parts:
60
- raise ValueError(f"Path traversal rejected in URI: {uri!r}")
72
+ raise WorkspaceContainmentError(f"Path traversal rejected in URI: {uri!r}")
61
73
  # On Windows, urlparse puts a leading '/' before the drive letter —
62
74
  # strip it so Path('C:/foo') is constructed correctly.
63
75
  if path.parts and path.parts[0] in ("/", "\\") and len(path.parts) > 1:
@@ -72,13 +84,41 @@ def uri_to_path(uri: str, workspace_root: Path | None = None) -> Path:
72
84
  try:
73
85
  resolved.relative_to(root_resolved)
74
86
  except ValueError:
75
- raise ValueError(
87
+ raise WorkspaceContainmentError(
76
88
  f"URI {uri!r} resolves to {resolved!r} which is outside the "
77
89
  f"workspace root {root_resolved!r}."
78
90
  )
79
91
  return resolved
80
92
 
81
93
 
94
+
95
+ def _invalidate_failed_review(server, state: _ServerState, uri: str) -> None:
96
+ """Fail closed at the LSP transport: old Rust results are no longer current."""
97
+ from lsprotocol import types as lsp_types
98
+
99
+ # Remove old CodeLens source before attempting I/O (publishing can itself fail).
100
+ state.diff_cache.pop(uri, None)
101
+ state.source_cache.pop(uri, None)
102
+ server.publish_diagnostics(uri, [
103
+ lsp_types.Diagnostic(
104
+ range=lsp_types.Range(
105
+ start=lsp_types.Position(line=0, character=0),
106
+ end=lsp_types.Position(line=0, character=0),
107
+ ),
108
+ severity=lsp_types.DiagnosticSeverity.Error,
109
+ message="IntentumDiff semantic review failed; previous results are invalid.",
110
+ source="intentumdiff",
111
+ )
112
+ ])
113
+ if state.supports_codelens_refresh:
114
+ try:
115
+ server.lsp.send_request("workspace/codeLens/refresh", None)
116
+ except Exception: # noqa: BLE001 - result stays invalidated.
117
+ log.debug("intentumdiff: failed CodeLens invalidation refresh", exc_info=True)
118
+
119
+
120
+
121
+
82
122
  # ---------------------------------------------------------------------------
83
123
  # Async diff scheduling
84
124
  # ---------------------------------------------------------------------------
@@ -109,18 +149,23 @@ async def _compute_and_push(
109
149
  await asyncio.sleep(state.debounce)
110
150
 
111
151
  loop = asyncio.get_running_loop()
112
- diff = await loop.run_in_executor(
113
- None, _do_diff, state, server, uri, content
152
+ result = await loop.run_in_executor(
153
+ None, _do_diff, state, server, uri, content, True
114
154
  )
115
- if diff is None:
155
+ if result is None:
156
+ # A failed Rust/Wasm review must not leave previously cached semantic
157
+ # CodeLens or diagnostics visible as though the current edit passed.
158
+ _invalidate_failed_review(server, state, uri)
116
159
  return
117
160
 
161
+ diff, old_source, new_source = result
118
162
  state.diff_cache[uri] = diff
163
+ state.source_cache[uri] = (old_source, new_source)
119
164
 
120
165
  # Publish diagnostics (push model — no client request needed).
121
166
  from intentumdiff.lsp_server._diagnostics import semantic_diff_to_diagnostics
122
167
 
123
- diags = semantic_diff_to_diagnostics(diff)
168
+ diags = semantic_diff_to_diagnostics(diff, new_source=new_source)
124
169
  server.publish_diagnostics(uri, diags)
125
170
 
126
171
  # Ask the client to refresh code-lens decorations when supported.
@@ -137,6 +182,12 @@ async def _compute_and_push(
137
182
  raise # propagate cancellation — do not swallow
138
183
  except Exception as exc: # noqa: BLE001
139
184
  log.warning("intentumdiff: unhandled error during diff for %s: %s", uri, exc)
185
+ # Even transport/publishing faults invalidate old semantic data. Never
186
+ # expose a stale successful review after the current review failed.
187
+ try:
188
+ _invalidate_failed_review(server, state, uri)
189
+ except Exception: # noqa: BLE001 - preserve the original failure log.
190
+ log.warning("intentumdiff: failed to publish review error for %s", uri, exc_info=True)
140
191
 
141
192
 
142
193
  # ---------------------------------------------------------------------------
@@ -148,7 +199,8 @@ def _do_diff(
148
199
  server,
149
200
  uri: str,
150
201
  content: str,
151
- ) -> SemanticDiff | None:
202
+ include_sources: bool = False,
203
+ ) -> SemanticDiff | tuple[SemanticDiff, str, str] | None:
152
204
  """Compute a ``SemanticDiff`` synchronously.
153
205
 
154
206
  Intended to be called via ``loop.run_in_executor`` so the event loop is
@@ -167,8 +219,14 @@ def _do_diff(
167
219
  file_path=str(rel_path),
168
220
  live_content=content,
169
221
  ref=state.ref,
222
+ cache_snapshot=include_sources,
170
223
  )
171
- return state.differ.diff(source)
224
+ diff = state.differ.diff(source)
225
+ if include_sources:
226
+ # The differ and LSP mapping must see the same old Git snapshot.
227
+ old_source, new_source, _, _ = source.get_content()
228
+ return diff, old_source, new_source
229
+ return diff
172
230
 
173
231
  except Exception as exc: # noqa: BLE001
174
232
  log.warning("intentumdiff: diff failed for %s: %s", uri, exc)