intentumdiff-python 0.0.1__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 (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/intentumdiff_rust_core.dll +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,837 @@
1
+ """
2
+ intentumdiff.core.models
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ All public and internal data models. Every model uses ``frozen=True`` so
6
+ instances are immutable and hashable — safe to use as dict keys / in sets.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from collections.abc import Mapping
13
+ from enum import Enum, IntEnum
14
+ from pathlib import Path, PurePosixPath
15
+ from types import MappingProxyType
16
+ from typing import NamedTuple, Any, Literal
17
+
18
+ from pydantic import (
19
+ BaseModel,
20
+ ConfigDict,
21
+ Field,
22
+ PrivateAttr,
23
+ field_serializer,
24
+ field_validator,
25
+ model_validator,
26
+ )
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # Fuel
30
+ # ---------------------------------------------------------------------------
31
+
32
+ FUEL_UNLIMITED: int = -1
33
+ """Sentinel for ``DiffConfig.plugin_fuel`` that disables the Wasm fuel cap.
34
+
35
+ Passing this value means plugins run without an instruction budget. Use with
36
+ care — a buggy plugin can spin forever. The CLI accepts ``--fuel inf`` as a
37
+ human-readable alias.
38
+ """
39
+
40
+
41
+ # ---------------------------------------------------------------------------
42
+ # Position
43
+ # ---------------------------------------------------------------------------
44
+
45
+
46
+ class NodePosition(BaseModel, frozen=True):
47
+ """Source-level span for a semantic node."""
48
+
49
+ start_line: int = Field(ge=0)
50
+ start_col: int = Field(ge=0)
51
+ end_line: int = Field(ge=0)
52
+ end_col: int = Field(ge=0)
53
+
54
+ @model_validator(mode="after")
55
+ def _end_after_start(self) -> NodePosition:
56
+ if (self.end_line, self.end_col) < (self.start_line, self.start_col):
57
+ raise ValueError("end position must be >= start position")
58
+ return self
59
+
60
+
61
+ # ---------------------------------------------------------------------------
62
+ # Detection
63
+ # ---------------------------------------------------------------------------
64
+
65
+
66
+ class DetectionResult(BaseModel, frozen=True):
67
+ """
68
+ Result of a content-based language detection query.
69
+
70
+ Returned by :meth:`~intentumdiff.SemanticDiffer.detect_language` and
71
+ :meth:`~intentumdiff.SemanticDiffer.detect_all`.
72
+ """
73
+
74
+ language: str = Field(min_length=1, description="Language ID (e.g. 'python', 'typescript').")
75
+ grammar_id: str = Field(min_length=1, description="Grammar ID of the matching parser plugin.")
76
+ confidence: float = Field(
77
+ default=1.0,
78
+ ge=0.0,
79
+ le=1.0,
80
+ description=(
81
+ "Relative confidence derived from parser priority order. "
82
+ "1.0 for the highest-priority match, lower for subsequent matches."
83
+ ),
84
+ )
85
+
86
+
87
+ class LanguagePluginInfo(BaseModel, frozen=True):
88
+ """Metadata for one parser plugin's handling of one language ID."""
89
+
90
+ model_config = ConfigDict(populate_by_name=True)
91
+
92
+ language_id: str = Field(alias="languageId", min_length=1)
93
+ language_name: str = Field(alias="languageName", min_length=1)
94
+ language_short_name: str = Field(alias="languageShortName", min_length=1)
95
+ monaco_language: str = Field(alias="monacoLanguage", min_length=1)
96
+ default_filename: str = Field(alias="defaultFilename", min_length=1)
97
+ language_file_extensions: list[str] = Field(
98
+ alias="languageFileExtensions", default_factory=list
99
+ )
100
+ author: str = ""
101
+ plugin_version: str = Field(alias="pluginVersion", default="")
102
+ last_updated: str = Field(alias="lastUpdated", default="")
103
+ plugin_id: str = Field(alias="pluginId", min_length=1)
104
+ grammar_id: str = Field(alias="grammarId", min_length=1)
105
+ priority: int = 0
106
+ is_trusted: bool = Field(alias="isTrusted", default=False)
107
+ provenance: str = ""
108
+
109
+
110
+ class LanguageInfoGroup(BaseModel, frozen=True):
111
+ """Grouped parser-plugin metadata for a language ID."""
112
+
113
+ model_config = ConfigDict(populate_by_name=True)
114
+
115
+ language: str = Field(min_length=1)
116
+ selected_plugin_id: str = Field(alias="selectedPluginId", min_length=1)
117
+ plugins: list[LanguagePluginInfo] = Field(default_factory=list)
118
+
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # Semantic tree
122
+ # ---------------------------------------------------------------------------
123
+
124
+
125
+ class NodeFacts(BaseModel, frozen=True):
126
+ """
127
+ Privacy-safe structural facts about a definition node (function/method/class),
128
+ computed by the Rust parser from the full CST before pruning. Only counts,
129
+ enums, and flags — never source text, identifiers, or literals — so they can
130
+ describe a change's shape ("no parameters", "returns nothing", "no-op body")
131
+ without revealing code. The host carries this through unchanged.
132
+ """
133
+
134
+ param_count: int | None = None
135
+ #: ``"none"`` | ``"value"`` | ``"literal"`` (constant) | ``"unknown"``.
136
+ returns: str | None = None
137
+ #: The KIND of constant returned when ``returns == "literal"`` —
138
+ #: ``"int"`` | ``"float"`` | ``"str"`` | ``"bool"`` | ``"none"`` | ``"mixed"``.
139
+ #: The kind only, never the literal value (privacy-safe).
140
+ return_kind: str | None = None
141
+ #: ``"empty"`` | ``"stub"`` | ``"substantive"``.
142
+ body: str | None = None
143
+ #: True when the body has a bare call statement (a side effect / output). Flag only.
144
+ side_effects: bool | None = None
145
+ #: Behavior classification (#69-H) — control-flow shape, flags/enum only.
146
+ has_conditional: bool | None = None
147
+ has_loop: bool | None = None
148
+ has_error_handling: bool | None = None
149
+ #: The body raises/throws an exception. Flag only.
150
+ throws: bool | None = None
151
+ #: The body mutates state — an augmented assignment or an assignment to an
152
+ #: attribute/subscript (``self.x = …``, ``a[i] = …``). Flag only, no target name.
153
+ mutates: bool | None = None
154
+ #: The body returns a freshly-built collection/object (list/dict/set/tuple/new/…).
155
+ #: A factory signal. Flag only, never the constructed value.
156
+ constructs: bool | None = None
157
+ #: Whether a *substantive* body performs actual computation (operators/comprehensions/
158
+ #: ternary) vs only calling out and returning. Explicit ``False`` is the #68 antidote —
159
+ #: it lets the explainer say "performs no computation" instead of inventing it. Emitted
160
+ #: only for substantive bodies; ``None`` for stub/empty bodies (nothing to assess).
161
+ has_computation: bool | None = None
162
+ #: ``"linear"`` | ``"branching"`` | ``"looping"`` — rollup of the above.
163
+ control_shape: str | None = None
164
+ #: Coarse "what kind of function" rollup — ``"accessor"`` | ``"transformer"`` |
165
+ #: ``"validator"`` | ``"io"`` | ``"mutator"`` | ``"factory"``. Purpose signal only.
166
+ behavior_category: str | None = None
167
+ is_async: bool | None = None
168
+ is_generator: bool | None = None
169
+ decorator_count: int | None = None
170
+ #: Class facts (#69 catalog D) — shape counts, from the class definition. Counts only.
171
+ method_count: int | None = None
172
+ field_count: int | None = None
173
+ base_count: int | None = None
174
+ #: Class kind, inferred from base classes (never the base NAME): an enumeration
175
+ #: (Enum/IntEnum/…) or an exception (Exception/BaseException/`*Error`/`*Warning`). Flags only.
176
+ is_enum: bool | None = None
177
+ is_exception: bool | None = None
178
+ #: Decorator semantics (#69 catalog C/D), inferred from decorator names but emitted as flags
179
+ #: only (never the decorator name): read-only property, static/class method, abstract member,
180
+ #: cached/memoized, and the dataclass class kind.
181
+ is_property: bool | None = None
182
+ is_staticmethod: bool | None = None
183
+ is_classmethod: bool | None = None
184
+ is_abstract: bool | None = None
185
+ is_cached: bool | None = None
186
+ is_dataclass: bool | None = None
187
+ #: Param kinds (#69 catalog C) — counts/flags only, never a parameter name: params with a
188
+ #: default (optional), keyword-only params (after `*`/`*args`), and variadic `*args`/`**kwargs`.
189
+ default_count: int | None = None
190
+ keyword_only_count: int | None = None
191
+ has_variadic: bool | None = None
192
+ has_kwargs: bool | None = None
193
+ #: Coupling (#69-J) — outbound-call fan-out count (call sites, no callee names) and whether the
194
+ #: function calls itself (recursion). Count/flag only.
195
+ call_count: int | None = None
196
+ recursive: bool | None = None
197
+
198
+
199
+ class SemanticNode(BaseModel, frozen=True):
200
+ """
201
+ A node in the language-specific semantic tree produced by a parser plugin.
202
+
203
+ ``structural_hash`` is computed by the host (via the WIT host-import
204
+ ``structural-hash``) so it is consistent across all plugins.
205
+ """
206
+
207
+ id: str = Field(min_length=1)
208
+ node_type: str = Field(min_length=1)
209
+ label: str
210
+ position: NodePosition
211
+ structural_hash: str = Field(min_length=1)
212
+ children: list[SemanticNode] = Field(default_factory=list)
213
+ # Class name that directly owns this node (set by parsers for methods).
214
+ # Used by PULL_UP / PUSH_DOWN refactoring detection.
215
+ parent_type: str | None = None
216
+ # Resolved type string from an LSP hover query (e.g. ``"int"``, ``"str | None"``).
217
+ # ``None`` when no LSP server is configured or the server has no info.
218
+ type_info: str | None = None
219
+ # Privacy-safe structural facts for definition nodes (functions/methods/classes),
220
+ # emitted by the Rust parser. Carried through unchanged to the extension.
221
+ facts: NodeFacts | None = None
222
+
223
+ # Memoisation caches — not part of the frozen public fields
224
+ _height_cache: int | None = PrivateAttr(default=None)
225
+ _descendants_cache: list[SemanticNode] | None = PrivateAttr(default=None)
226
+
227
+ def is_leaf(self) -> bool:
228
+ return len(self.children) == 0
229
+
230
+ def height(self) -> int:
231
+ if self._height_cache is None:
232
+ h = 0 if self.is_leaf() else 1 + max(c.height() for c in self.children)
233
+ object.__setattr__(self, "_height_cache", h)
234
+ return self._height_cache # type: ignore[return-value]
235
+
236
+ def descendants(self) -> list[SemanticNode]:
237
+ if self._descendants_cache is None:
238
+ result: list[SemanticNode] = []
239
+ for child in self.children:
240
+ result.append(child)
241
+ result.extend(child.descendants())
242
+ object.__setattr__(self, "_descendants_cache", result)
243
+ return self._descendants_cache # type: ignore[return-value]
244
+
245
+
246
+ # ---------------------------------------------------------------------------
247
+ # Reference taxonomy
248
+ # ---------------------------------------------------------------------------
249
+
250
+
251
+ class ReferenceKind(str, Enum):
252
+ """The kind of usage a ``ReferenceUsage`` represents."""
253
+
254
+ CALL = "CALL"
255
+ IMPORT = "IMPORT"
256
+ TYPE_USAGE = "TYPE_USAGE"
257
+
258
+
259
+ # ---------------------------------------------------------------------------
260
+ # Change taxonomy
261
+ # ---------------------------------------------------------------------------
262
+
263
+
264
+ # ---------------------------------------------------------------------------
265
+ # Streaming change events
266
+ # ---------------------------------------------------------------------------
267
+
268
+
269
+ class ChangeStreamPhase(IntEnum):
270
+ """Phase of the analysis pipeline that produced a streaming event."""
271
+
272
+ STRUCTURAL = 1
273
+ """After edit-script computation and move promotion (stage 11)."""
274
+ REFINED = 2
275
+ """After refactoring detection (stage 12)."""
276
+ FINAL = 3
277
+ """After classification and diff-analyzer passes (stages 13–13.5)."""
278
+
279
+
280
+ class ChangeType(str, Enum):
281
+ ADDITION = "ADDITION"
282
+ DELETION = "DELETION"
283
+ MODIFICATION = "MODIFICATION"
284
+ MOVE = "MOVE"
285
+ REORDER = "REORDER"
286
+ STYLE_ONLY = "STYLE_ONLY"
287
+ REFACTORING = "REFACTORING"
288
+ # Cross-file change types (populated by CommitDiffer / SemanticIndex)
289
+ MOVE_TO_MODULE = "MOVE_TO_MODULE"
290
+ CROSS_FILE_RENAME = "CROSS_FILE_RENAME"
291
+ SPLIT_MODULE = "SPLIT_MODULE"
292
+
293
+
294
+ class GuardrailSeverity(str, Enum):
295
+ """Severity for project-level protected semantic changes."""
296
+
297
+ IMPORTANT = "important"
298
+ IMMUTABLE = "immutable"
299
+
300
+
301
+ class RefactoringKind(str, Enum):
302
+ RENAME_SYMBOL = "RENAME_SYMBOL"
303
+ RENAME_CLASS = "RENAME_CLASS"
304
+ RENAME_METHOD = "RENAME_METHOD"
305
+ RENAME_VARIABLE = "RENAME_VARIABLE"
306
+ EXTRACT_FUNCTION = "EXTRACT_FUNCTION"
307
+ INLINE_FUNCTION = "INLINE_FUNCTION"
308
+ CHANGE_SIGNATURE = "CHANGE_SIGNATURE"
309
+ PULL_UP = "PULL_UP"
310
+ PUSH_DOWN = "PUSH_DOWN"
311
+ EXTRACT_CLASS = "EXTRACT_CLASS"
312
+ INLINE_CLASS = "INLINE_CLASS"
313
+ INLINE_VARIABLE = "INLINE_VARIABLE"
314
+ EXTRACT_VARIABLE = "EXTRACT_VARIABLE"
315
+ MERGE_METHOD = "MERGE_METHOD"
316
+ INTRODUCE_PARAMETER_OBJECT = "INTRODUCE_PARAMETER_OBJECT"
317
+ REPLACE_CONDITIONAL_WITH_POLYMORPHISM = "REPLACE_CONDITIONAL_WITH_POLYMORPHISM"
318
+ REPLACE_LOOP_WITH_PIPELINE = "REPLACE_LOOP_WITH_PIPELINE"
319
+
320
+
321
+ class ChangeGroupKind(str, Enum):
322
+ """Review-level grouping for related raw change events."""
323
+
324
+ MOVED_CODE = "MOVED_CODE"
325
+ REFACTORING = "REFACTORING"
326
+ MEANINGFUL_CHANGE = "MEANINGFUL_CHANGE"
327
+ IGNORED_STYLE = "IGNORED_STYLE"
328
+ NOISE_SUPPRESSED = "NOISE_SUPPRESSED"
329
+
330
+
331
+ class Change(BaseModel, frozen=True):
332
+ """A single semantic change between two versions of a file."""
333
+
334
+ change_type: ChangeType | str
335
+ old_node: SemanticNode | None = None
336
+ new_node: SemanticNode | None = None
337
+ refactoring_kind: RefactoringKind | None = None
338
+ confidence: float = Field(ge=0.0, le=1.0, default=1.0)
339
+ description: str = ""
340
+ # Inline character-level diff for leaf MODIFICATION changes (e.g. "foo[-Bar][+Baz]")
341
+ text_diff: str | None = None
342
+ # Sibling indices for REORDER changes
343
+ old_index: int | None = None
344
+ new_index: int | None = None
345
+
346
+ @field_validator("change_type", mode="before")
347
+ @classmethod
348
+ def _normalise_change_type(cls, value: Any) -> ChangeType | str:
349
+ if isinstance(value, ChangeType):
350
+ return value
351
+ if isinstance(value, str):
352
+ try:
353
+ return ChangeType(value)
354
+ except ValueError:
355
+ return value
356
+ return value
357
+
358
+ @model_validator(mode="after")
359
+ def _node_consistency(self) -> Change:
360
+ t = self.change_type
361
+ if t == ChangeType.ADDITION and self.old_node is not None:
362
+ raise ValueError("ADDITION must not have an old_node")
363
+ if t == ChangeType.DELETION and self.new_node is not None:
364
+ raise ValueError("DELETION must not have a new_node")
365
+ if t == ChangeType.REFACTORING and self.refactoring_kind is None:
366
+ raise ValueError("REFACTORING requires a refactoring_kind")
367
+ return self
368
+
369
+
370
+ class ChangeGroup(BaseModel, frozen=True):
371
+ """A higher-level semantic grouping backed by raw change evidence."""
372
+
373
+ kind: ChangeGroupKind
374
+ raw_change_indices: list[int] = Field(default_factory=list)
375
+ old_labels: list[str] = Field(default_factory=list)
376
+ new_labels: list[str] = Field(default_factory=list)
377
+ old_node_ids: list[str] = Field(default_factory=list)
378
+ new_node_ids: list[str] = Field(default_factory=list)
379
+ confidence: float = Field(ge=0.0, le=1.0, default=1.0)
380
+ rule_id: str = ""
381
+ refactoring_kind: RefactoringKind | None = None
382
+ metadata: Mapping[str, Any] = Field(default_factory=dict)
383
+
384
+ @field_validator("metadata", mode="before")
385
+ @classmethod
386
+ def _normalise_metadata(cls, v: Any) -> dict[str, Any]:
387
+ return dict(v) if v is not None else {}
388
+
389
+ @field_validator("metadata")
390
+ @classmethod
391
+ def _freeze_metadata(cls, v: Mapping[str, Any]) -> MappingProxyType:
392
+ if isinstance(v, MappingProxyType):
393
+ return v
394
+ return MappingProxyType(dict(v))
395
+
396
+ @field_serializer("metadata")
397
+ def _serialize_metadata(self, v: Mapping[str, Any]) -> dict[str, Any]:
398
+ return dict(v)
399
+
400
+
401
+ class ChangeStreamEvent(BaseModel, frozen=True):
402
+ """A single event emitted by ``SemanticDiffer.diff_stream_progressive``.
403
+
404
+ Events are ordered: STRUCTURAL (phase 1) events arrive first, followed by
405
+ REFINED (phase 2) events that may revise or supersede them, and finally
406
+ FINAL (phase 3) events from the classification and diff-analyzer passes.
407
+
408
+ ``replaced_ids`` contains the ``old_node.id`` / ``new_node.id`` values of
409
+ Phase-1 changes that this event supersedes. When ``action="revise"`` the
410
+ consumer should look up prior events by these IDs and replace them. When
411
+ ``action="remove"`` there is no replacement — the change was absorbed.
412
+ """
413
+
414
+ phase: ChangeStreamPhase
415
+ action: Literal["add", "revise", "remove"]
416
+ change: Change | None = None
417
+ replaced_ids: list[str] = Field(default_factory=list)
418
+
419
+
420
+ # ---------------------------------------------------------------------------
421
+ # Diff result
422
+ # ---------------------------------------------------------------------------
423
+
424
+
425
+ class SemanticDiff(BaseModel, frozen=True):
426
+ """The complete semantic diff between two versions of a single file."""
427
+
428
+ model_config = ConfigDict(arbitrary_types_allowed=True)
429
+
430
+ guardrail_violations: list[GuardrailViolation] = Field(default_factory=list)
431
+ changes: list[Change] = Field(default_factory=list)
432
+ change_groups: list[ChangeGroup] = Field(default_factory=list)
433
+ old_filename: str
434
+ new_filename: str
435
+ language: str
436
+ has_semantic_changes: bool = False
437
+ is_style_only: bool = False
438
+ parse_errors: list[str] = Field(default_factory=list)
439
+ llm_summary: str = ""
440
+ gitignore_excluded: bool = False
441
+ # True when the parse step encountered errors and a token-level fallback was used
442
+ is_fallback: bool = False
443
+ # Describes where the change came from in the git lifecycle:
444
+ # "unstaged" = saved but not staged, "staged" = git-add'd, "unpushed" = committed but not
445
+ # yet pushed to the remote. None for an ordinary commit-to-commit diff.
446
+ staging_status: str | None = None
447
+ metadata: Mapping[str, Any] = Field(default_factory=dict)
448
+
449
+ @field_validator("metadata", mode="before")
450
+ @classmethod
451
+ def _normalise_metadata(cls, v: Any) -> dict[str, Any]:
452
+ return dict(v) if v is not None else {}
453
+
454
+ @field_validator("metadata")
455
+ @classmethod
456
+ def _freeze_metadata(cls, v: Mapping[str, Any]) -> MappingProxyType:
457
+ if isinstance(v, MappingProxyType):
458
+ return v
459
+ return MappingProxyType(dict(v))
460
+
461
+ @field_serializer("metadata")
462
+ def _serialize_metadata(self, v: Mapping[str, Any]) -> dict[str, Any]:
463
+ return dict(v)
464
+
465
+ @model_validator(mode="after")
466
+ def _style_only_is_no_changes(self) -> SemanticDiff:
467
+ if self.is_style_only and self.has_semantic_changes:
468
+ raise ValueError(
469
+ "is_style_only and has_semantic_changes cannot both be True"
470
+ )
471
+ return self
472
+
473
+ @classmethod
474
+ def style_only(
475
+ cls,
476
+ old_filename: str,
477
+ new_filename: str,
478
+ language: str,
479
+ *,
480
+ change_groups: list[ChangeGroup] | None = None,
481
+ metadata: Mapping[str, Any] | None = None,
482
+ ) -> SemanticDiff:
483
+ """Convenience constructor for the style-only shortcut."""
484
+ return cls(
485
+ old_filename=old_filename,
486
+ new_filename=new_filename,
487
+ language=language,
488
+ change_groups=change_groups or [],
489
+ has_semantic_changes=False,
490
+ is_style_only=True,
491
+ metadata=metadata or {},
492
+ )
493
+
494
+ @property
495
+ def file_renamed(self) -> bool:
496
+ """True when the file was renamed in-place (same directory, different basename)."""
497
+ old = PurePosixPath(self.old_filename)
498
+ new = PurePosixPath(self.new_filename)
499
+ return old.name != new.name and old.parent == new.parent
500
+
501
+ @property
502
+ def file_moved(self) -> bool:
503
+ """True when the file was moved to a different directory (with or without rename)."""
504
+ return (
505
+ PurePosixPath(self.old_filename).parent
506
+ != PurePosixPath(self.new_filename).parent
507
+ )
508
+
509
+
510
+ # ---------------------------------------------------------------------------
511
+ # Incremental parse hint
512
+ # ---------------------------------------------------------------------------
513
+
514
+
515
+ class EditDelta(BaseModel, frozen=True):
516
+ """A single byte-range edit used to drive incremental tree-sitter parsing.
517
+
518
+ Mirrors the arguments to ``tree_sitter.Tree.edit()`` so that a caller
519
+ (e.g. ``LiveServer``) can pass precise edit information to the differ and
520
+ avoid a full re-parse.
521
+
522
+ All byte offsets are measured from the *start of the file*. Points are
523
+ ``(row, column)`` tuples using **0-based** row and column indices,
524
+ consistent with the tree-sitter convention.
525
+ """
526
+
527
+ start_byte: int = Field(ge=0)
528
+ old_end_byte: int = Field(ge=0)
529
+ new_end_byte: int = Field(ge=0)
530
+ start_point: tuple[int, int]
531
+ old_end_point: tuple[int, int]
532
+ new_end_point: tuple[int, int]
533
+
534
+
535
+ # ---------------------------------------------------------------------------
536
+ # Configuration
537
+ # ---------------------------------------------------------------------------
538
+
539
+
540
+ def _native_rust_core_default() -> bool:
541
+ """Return the default certified Rust-core policy.
542
+
543
+ IntentumDiff ships the first-party Rust core in release wheels, so supported
544
+ native paths should use it automatically. The legacy
545
+ ``INTENTUMDIFF_EXPERIMENTAL_RUST_CORE`` env var is still accepted for compatibility,
546
+ while ``INTENTUMDIFF_RUST_CORE=0`` is the explicit fallback escape hatch.
547
+ """
548
+
549
+ raw = os.getenv("INTENTUMDIFF_RUST_CORE")
550
+ if raw is None:
551
+ raw = os.getenv("INTENTUMDIFF_EXPERIMENTAL_RUST_CORE")
552
+ if raw is None or raw.strip() == "":
553
+ return True
554
+ return raw.strip().lower() in {"1", "true", "yes", "on", "auto", "native"}
555
+
556
+
557
+ class Match(NamedTuple):
558
+ """A matched (old, new) node pair from the tree matcher (Rust core)."""
559
+
560
+ old_node: SemanticNode
561
+ new_node: SemanticNode
562
+
563
+
564
+ Matching = list[Match]
565
+
566
+
567
+ class DiffConfig(BaseModel):
568
+ """
569
+ Configuration for the diffing pipeline.
570
+
571
+ Unlike result models, this is NOT frozen — callers may update it freely
572
+ before passing to ``SemanticDiffer``.
573
+ """
574
+
575
+ # GumTree tuning
576
+ min_similarity: float = Field(default=0.5, ge=0.0, le=1.0)
577
+ approx_move_threshold: float = Field(default=0.4, ge=0.0, le=1.0)
578
+ min_height: int = Field(default=2, ge=0)
579
+
580
+ # Feature flags
581
+ ignore_style: bool = True
582
+ detect_refactorings: bool = True
583
+ diagnostics: bool = False
584
+ profile_phases: bool = Field(
585
+ default_factory=lambda: os.getenv("INTENTUMDIFF_PROFILE_PHASES", "").strip().lower()
586
+ in {"1", "true", "yes", "on"},
587
+ )
588
+ """Attach opt-in phase timing metadata to diff results."""
589
+ experimental_rust_core: bool = Field(
590
+ default_factory=_native_rust_core_default,
591
+ )
592
+ """Use the certified Rust core for supported first-party native paths."""
593
+ diagnostics_max_events: int = Field(default=500, ge=0)
594
+ guardrails_enabled: bool = True
595
+ guardrails_strict: bool = False
596
+ guardrail_policy_path: Path | None = None
597
+
598
+ # Test-only override for the GumTree matching stage. Production code
599
+ # leaves this as ``None`` and the pipeline picks the matching engine
600
+ # based on ``experimental_rust_core`` and the certified-surfaces check.
601
+ # Truthiness tests set this to ``"rust"`` or ``"python"`` to force one
602
+ # matcher so the dual-run matrix can certify both contracts. See
603
+ # ``the retired NOISE_SUPPRESSION_RETUNE doc (git history)`` and the dual-run fixture in
604
+ # ``tests/unit/test_wild_truthiness_regressions.py``.
605
+ test_matching_engine: Literal["rust", "python"] | None = None
606
+
607
+ # Extra CST node types to treat as trivia (merged with plugin defaults)
608
+ extra_trivia_types: list[str] = Field(default_factory=list)
609
+
610
+ # Plugin control
611
+ allowed_plugins: list[str] | None = None
612
+ strict_plugins: bool = False
613
+
614
+ # Safety limits
615
+ plugin_fuel: int = Field(default=100_000_000)
616
+ """Wasm instruction budget per plugin call. Use ``FUEL_UNLIMITED`` (``-1``)
617
+ to remove the cap entirely."""
618
+
619
+ @field_validator("plugin_fuel")
620
+ @classmethod
621
+ def _validate_plugin_fuel(cls, v: int) -> int:
622
+ if v == FUEL_UNLIMITED:
623
+ return v
624
+ if v < 1:
625
+ raise ValueError(
626
+ "plugin_fuel must be a positive integer or FUEL_UNLIMITED (-1)"
627
+ )
628
+ return v
629
+ max_nodes: int = Field(default=50_000, ge=1)
630
+ # Maximum CST JSON size (in characters) accepted at the Wasm boundary.
631
+ # Files whose serialised CST exceeds this are rejected with a clear error
632
+ # rather than silently passing megabytes into the plugin sandbox.
633
+ max_cst_bytes: int = Field(default=4 * 1024 * 1024, ge=1) # 4 MB
634
+ max_plugin_output_bytes: int = Field(default=16 * 1024 * 1024, ge=1)
635
+ """Maximum text returned by a single Wasm plugin export before rejection."""
636
+
637
+ # Compatibility field retained for older callers. Public parser hosting is
638
+ # Rust/Wasm FullParse-only, so Python tree-sitter grammar factories are
639
+ # accepted in config objects but are not used by the product path.
640
+ extra_grammars: dict[str, Any] = Field(default_factory=dict)
641
+
642
+ # Reference resolution
643
+ resolve_references: bool = False
644
+
645
+ # ── Caching / persistence ────────────────────────────────────────────────
646
+ # Set ``cache_path`` to a directory to enable the SQLite parse + diff
647
+ # cache. The database is written to ``<cache_path>/cache.db``.
648
+ # Set ``analytics_path`` to also record every diff in a DuckDB history
649
+ # table at ``<analytics_path>/analytics.duckdb`` (requires ``duckdb``).
650
+ cache_path: Path | None = Field(default=None)
651
+ cache_ttl_days: int = Field(default=30, ge=1)
652
+ cache_max_mb: int = Field(default=500, ge=1)
653
+ analytics_path: Path | None = Field(default=None)
654
+
655
+ # ── LSP type enrichment ──────────────────────────────────────────────────
656
+ # Map from language name to ``LspServerConfig``. When set, the indexer
657
+ # connects to the corresponding server and attaches ``type_info`` to
658
+ # ``SemanticNode`` leaves before diffing. Requires the optional
659
+ # ``lsprotocol`` dependency and a running language server.
660
+ #
661
+ # Example CLI usage::
662
+ #
663
+ # intentumdiff index . --lsp python=localhost:2087
664
+ lsp_servers: dict[str, Any] | None = Field(default=None)
665
+ """Map of language → ``LspServerConfig``. Type is ``Any`` to avoid a
666
+ hard dependency on the optional ``lsprotocol`` package in core models."""
667
+
668
+ lsp_timeout: float = Field(default=5.0, gt=0.0)
669
+ """Per-request timeout (seconds) for LSP hover calls."""
670
+
671
+ # ── Execution ─────────────────────────────────────────────────────────────
672
+ parallel: int | bool = False
673
+ """Fan-out commit-wide diffs across threads.
674
+
675
+ - ``False`` (default): sequential execution.
676
+ - ``True``: use ``os.cpu_count()`` threads.
677
+ - Positive ``int``: explicit worker count.
678
+ """
679
+
680
+ @field_validator("parallel")
681
+ @classmethod
682
+ def _validate_parallel(cls, v: int | bool) -> int | bool:
683
+ if isinstance(v, bool):
684
+ return v
685
+ if v < 0:
686
+ raise ValueError("parallel must be False, True, or a positive integer")
687
+ return v
688
+
689
+ # ── Diff quality ─────────────────────────────────────────────────────────
690
+ leaf_text_diff: bool = True
691
+ """Annotate leaf-node MODIFICATION changes with a character-level inline diff
692
+ stored in ``Change.text_diff``."""
693
+
694
+ fallback_to_token_diff: bool = True
695
+ """When the parser produces a tree containing ERROR nodes, fall back to a
696
+ coarse token-level diff instead of running GumTree. The resulting
697
+ ``SemanticDiff`` will have ``is_fallback=True``."""
698
+
699
+ stream_analysis: bool = False
700
+ """Enable progressive per-phase streaming via ``diff_stream_progressive``.
701
+
702
+ When ``True``, callers may iterate ``SemanticDiffer.diff_stream_progressive``
703
+ to receive ``ChangeStreamEvent`` objects as each pipeline phase completes,
704
+ rather than waiting for the entire pipeline to finish."""
705
+
706
+
707
+ # ---------------------------------------------------------------------------
708
+ # Cross-file semantic analysis models
709
+ # ---------------------------------------------------------------------------
710
+
711
+
712
+ class SymbolDefinition(BaseModel, frozen=True):
713
+ """A symbol (function, class, etc.) defined in a specific file."""
714
+
715
+ qualified_name: str = Field(min_length=1)
716
+ file: str = Field(min_length=1)
717
+ node_type: str = Field(min_length=1)
718
+ node_id: str = Field(min_length=1)
719
+ start_line: int = Field(ge=0)
720
+ start_col: int = Field(ge=0)
721
+ end_line: int = Field(ge=0)
722
+ end_col: int = Field(ge=0)
723
+ language: str = ""
724
+
725
+
726
+ class ReferenceUsage(BaseModel, frozen=True):
727
+ """A call-site, import, or type-annotation usage of a named symbol."""
728
+
729
+ qualified_name: str = Field(min_length=1)
730
+ file: str = Field(min_length=1)
731
+ node_id: str = Field(min_length=1)
732
+ reference_kind: ReferenceKind
733
+ position: NodePosition
734
+ language: str = ""
735
+ # Dot-qualified name of the enclosing definition (e.g. "MyClass.method").
736
+ # ``None`` for usages at module scope.
737
+ enclosing_scope: str | None = None
738
+ # Populated by ``SemanticIndex.find_references(name, resolve=True)`` when
739
+ # exactly one matching definition is found in the same index.
740
+ resolved_definition: SymbolDefinition | None = None
741
+
742
+
743
+ class CrossFileChange(BaseModel, frozen=True):
744
+ """A semantic change that spans multiple files in a commit."""
745
+
746
+ change_type: ChangeType | str
747
+ symbol_name: str = Field(min_length=1)
748
+ old_file: str
749
+ new_file: str
750
+ old_node_id: str | None = None
751
+ new_node_id: str | None = None
752
+ old_position: NodePosition | None = None
753
+ new_position: NodePosition | None = None
754
+ old_language: str = ""
755
+ new_language: str = ""
756
+ node_type: str = ""
757
+ symbol_kind: str = ""
758
+ confidence: float = Field(ge=0.0, le=1.0, default=1.0)
759
+ description: str = ""
760
+
761
+
762
+ class GuardrailViolation(BaseModel, frozen=True):
763
+ """A project policy rule matched a protected semantic change."""
764
+
765
+ rule_id: str = Field(min_length=1)
766
+ severity: GuardrailSeverity
767
+ file: str = Field(min_length=1)
768
+ language: str = ""
769
+ semantic_path: str = Field(min_length=1)
770
+ node_type: str = ""
771
+ old_node_id: str | None = None
772
+ new_node_id: str | None = None
773
+ position: NodePosition | None = None
774
+ old_value: str = ""
775
+ new_value: str = ""
776
+ message: str = ""
777
+
778
+
779
+ class GuardrailCheckResult(BaseModel, frozen=True):
780
+ """CI-friendly summary of protected semantic guardrail evaluation."""
781
+
782
+ model_config = ConfigDict(arbitrary_types_allowed=True)
783
+
784
+ violations: list[GuardrailViolation] = Field(default_factory=list)
785
+ violation_count: int = 0
786
+ immutable_count: int = 0
787
+ important_count: int = 0
788
+ checked_files: int = 0
789
+ strict: bool = False
790
+ passed: bool = True
791
+ metadata: Mapping[str, Any] = Field(default_factory=dict)
792
+
793
+ @field_validator("metadata", mode="before")
794
+ @classmethod
795
+ def _normalise_metadata(cls, v: Any) -> dict[str, Any]:
796
+ return dict(v) if v is not None else {}
797
+
798
+ @field_validator("metadata")
799
+ @classmethod
800
+ def _freeze_metadata(cls, v: Mapping[str, Any]) -> MappingProxyType:
801
+ if isinstance(v, MappingProxyType):
802
+ return v
803
+ return MappingProxyType(dict(v))
804
+
805
+ @field_serializer("metadata")
806
+ def _serialize_metadata(self, v: Mapping[str, Any]) -> dict[str, Any]:
807
+ return dict(v)
808
+
809
+ @model_validator(mode="after")
810
+ def _derive_counts(self) -> GuardrailCheckResult:
811
+ immutable_count = sum(
812
+ violation.severity == GuardrailSeverity.IMMUTABLE
813
+ for violation in self.violations
814
+ )
815
+ important_count = sum(
816
+ violation.severity == GuardrailSeverity.IMPORTANT
817
+ for violation in self.violations
818
+ )
819
+ object.__setattr__(self, "violation_count", len(self.violations))
820
+ object.__setattr__(self, "immutable_count", immutable_count)
821
+ object.__setattr__(self, "important_count", important_count)
822
+ object.__setattr__(self, "passed", not (self.strict and immutable_count))
823
+ return self
824
+
825
+
826
+ class CommitDiff(BaseModel, frozen=True):
827
+ """
828
+ The full semantic diff for a commit: per-file diffs plus cross-file
829
+ changes detected by SemanticIndex comparison.
830
+ """
831
+
832
+ old_ref: str
833
+ new_ref: str
834
+ guardrail_violations: list[GuardrailViolation] = Field(default_factory=list)
835
+ file_diffs: list[SemanticDiff] = Field(default_factory=list)
836
+ cross_file_changes: list[CrossFileChange] = Field(default_factory=list)
837
+ parse_errors: list[str] = Field(default_factory=list)