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,644 @@
1
+ """
2
+ intentumdiff.cli
3
+ ~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Command-line interface for IntentumDiff.
6
+
7
+ Usage
8
+ -----
9
+ intentumdiff git <repo> <file> [--old REF] [--new REF] [--format FORMAT] [--output FILE]
10
+ intentumdiff file <old-file> <new-file> [--format FORMAT] [--output FILE]
11
+ intentumdiff patch [PATCH_FILE] [--base BASE_FILE]
12
+ intentumdiff string <old> <new> [--lang LANG]
13
+ intentumdiff plugins List installed parser and renderer plugins
14
+
15
+ Formats: terminal (default), terminal-color, json, patch, html, llm
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import json
22
+ import os
23
+ import shlex
24
+ import sys
25
+ import time
26
+ from contextlib import suppress
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ try: # rich-click is a runtime dependency, but this fallback keeps source-tree tests robust.
31
+ import rich_click as click
32
+ _CLICK_RUNTIME_AVAILABLE = True
33
+ except ModuleNotFoundError: # pragma: no cover - exercised only in minimal dev envs.
34
+ _CLICK_RUNTIME_AVAILABLE = False
35
+ click = None # type: ignore[assignment]
36
+
37
+ from rich import box
38
+ from rich.console import Console
39
+ from rich.panel import Panel
40
+ from rich.table import Table
41
+ from rich.text import Text
42
+
43
+ from intentumdiff import (
44
+ DiffConfig,
45
+ GuardrailCheckResult,
46
+ GuardrailSeverity,
47
+ SemanticDiff,
48
+ SemanticDiffer,
49
+ __version__,
50
+ )
51
+ from intentumdiff.analysis.guardrail_reports import (
52
+ guardrail_result_from_diffs,
53
+ render_guardrail_annotations,
54
+ render_guardrail_json,
55
+ render_guardrail_sarif,
56
+ )
57
+ from intentumdiff.core.config import load_project_diff_config
58
+
59
+ _console = Console()
60
+ _err = Console(stderr=True, highlight=False)
61
+
62
+ _NO_BANNER_ENV = "INTENTUMDIFF_NO_BANNER"
63
+ _MACHINE_PROTOCOL_COMMANDS = {"live-server", "lsp-server"}
64
+ _MACHINE_OUTPUT_FORMATS = {"json", "patch", "html", "llm", "sarif"}
65
+
66
+
67
+ # ---------------------------------------------------------------------------
68
+ # Helpers
69
+ # ---------------------------------------------------------------------------
70
+
71
+
72
+ def _differ(
73
+ fuel: int | None = None,
74
+ resolve_references: bool = False,
75
+ parallel: int | bool | None = None,
76
+ diagnostics: bool = False,
77
+ profile_phases: bool = False,
78
+ guardrails_strict: bool = False,
79
+ config_start_path: str | Path | None = None,
80
+ guardrails_policy: str | Path | None = None,
81
+ ) -> SemanticDiffer:
82
+ cfg = _load_cli_config(fuel=fuel, config_start_path=config_start_path)
83
+ cfg.resolve_references = resolve_references
84
+ cfg.diagnostics = diagnostics
85
+ if profile_phases:
86
+ cfg.profile_phases = True
87
+ cfg.guardrails_strict = guardrails_strict
88
+ if guardrails_policy is not None:
89
+ cfg.guardrail_policy_path = Path(guardrails_policy)
90
+ if parallel is not None:
91
+ cfg.parallel = parallel
92
+ return SemanticDiffer(cfg)
93
+
94
+
95
+ def _load_cli_config(
96
+ *,
97
+ fuel: int | None = None,
98
+ config_start_path: str | Path | None = None,
99
+ ) -> DiffConfig:
100
+ cfg = load_project_diff_config(config_start_path)
101
+ if fuel is not None:
102
+ cfg.plugin_fuel = fuel
103
+ _warn_if_unlimited_fuel(cfg.plugin_fuel)
104
+ return cfg
105
+
106
+
107
+ def _banner_disabled_by_env() -> bool:
108
+ value = os.environ.get(_NO_BANNER_ENV, "")
109
+ return value.strip().lower() in {"1", "true", "yes", "on"}
110
+
111
+
112
+ def _render_cli_banner(
113
+ *,
114
+ compact: bool = False,
115
+ console: Console | None = None,
116
+ ) -> None:
117
+ """Render the IntentumDiff banner for interactive CLI sessions."""
118
+ out = console or _console
119
+ title = Text("IntentumDiff", style="bold cyan")
120
+ body = Text.assemble(
121
+ ("Semantic review shell", "bold yellow"),
122
+ (" ", "dim"),
123
+ (f"v{__version__}", "dim"),
124
+ "\n",
125
+ ("Diff with meaning. Moves, intent, guardrails, and review signals.", "dim"),
126
+ )
127
+ if compact:
128
+ out.print(Panel(body, title=title, border_style="cyan", box=box.ROUNDED, expand=False))
129
+ return
130
+
131
+ out.print(
132
+ Panel(
133
+ body,
134
+ title=title,
135
+ subtitle=Text("type help for commands", style="dim"),
136
+ border_style="cyan",
137
+ box=box.ROUNDED,
138
+ expand=False,
139
+ padding=(1, 2),
140
+ )
141
+ )
142
+ out.print()
143
+
144
+
145
+ def _version_text() -> str:
146
+ return f"IntentumDiff {__version__}"
147
+
148
+
149
+ def _is_machine_output(args: argparse.Namespace) -> bool:
150
+ if getattr(args, "command", None) in _MACHINE_PROTOCOL_COMMANDS:
151
+ return True
152
+ if getattr(args, "format", "terminal") in _MACHINE_OUTPUT_FORMATS:
153
+ return True
154
+ if getattr(args, "command", None) == "assets" and getattr(args, "json", False):
155
+ return True
156
+ if getattr(args, "output", None):
157
+ return True
158
+ if getattr(args, "command", None) == "cache" and getattr(
159
+ args,
160
+ "cache_command",
161
+ None,
162
+ ) == "export":
163
+ return True
164
+ return (
165
+ getattr(args, "command", None) == "diagnostics"
166
+ and getattr(args, "format", "terminal") == "json"
167
+ or getattr(args, "command", None) == "watch"
168
+ and getattr(args, "live_stdin", False)
169
+ )
170
+
171
+
172
+ def _should_show_cli_banner(
173
+ args: argparse.Namespace,
174
+ *,
175
+ is_terminal: bool | None = None,
176
+ ) -> bool:
177
+ if getattr(args, "no_banner", False) or _banner_disabled_by_env():
178
+ return False
179
+ if getattr(args, "command", None) == "shell":
180
+ return False
181
+ if _is_machine_output(args):
182
+ return False
183
+ terminal = _console.is_terminal if is_terminal is None else is_terminal
184
+ return bool(terminal)
185
+
186
+
187
+ def _maybe_render_cli_banner(args: argparse.Namespace) -> None:
188
+ if _should_show_cli_banner(args):
189
+ _render_cli_banner(compact=True)
190
+
191
+
192
+ def _run_parsed_command(
193
+ args: argparse.Namespace,
194
+ *,
195
+ show_banner: bool = True,
196
+ ) -> None:
197
+ if show_banner:
198
+ _maybe_render_cli_banner(args)
199
+ args.func(args)
200
+
201
+
202
+ def _print_shell_help(parser: argparse.ArgumentParser, words: list[str]) -> None:
203
+ if not words:
204
+ parser.print_help()
205
+ return
206
+ try:
207
+ parser.parse_args([*words, "--help"])
208
+ except SystemExit:
209
+ return
210
+
211
+
212
+ def _run_shell_line(line: str, parser: argparse.ArgumentParser) -> bool:
213
+ """Run one shell line. Return False when the shell should exit."""
214
+ stripped = line.strip()
215
+ if not stripped:
216
+ return True
217
+ if stripped in {"exit", "quit"}:
218
+ return False
219
+ if stripped == "version":
220
+ _console.print(_version_text())
221
+ return True
222
+
223
+ try:
224
+ words = shlex.split(stripped)
225
+ except ValueError as exc:
226
+ _err.print(f"[red]Parse error:[/red] {exc}")
227
+ return True
228
+ if not words:
229
+ return True
230
+ if words[0] == "help":
231
+ _print_shell_help(parser, words[1:])
232
+ return True
233
+
234
+ try:
235
+ args = parser.parse_args(words)
236
+ except SystemExit:
237
+ return True
238
+ if getattr(args, "command", None) == "shell":
239
+ _err.print("[yellow]Already inside the IntentumDiff shell.[/yellow]")
240
+ return True
241
+ try:
242
+ args.no_banner = True
243
+ _run_parsed_command(args, show_banner=False)
244
+ except KeyboardInterrupt:
245
+ _err.print("\n[dim]Command interrupted.[/dim]")
246
+ except Exception as exc: # noqa: BLE001
247
+ _err.print(f"[red]Error:[/red] {exc}")
248
+ return True
249
+
250
+
251
+ def _cmd_shell(args: argparse.Namespace) -> None:
252
+ """Start a lightweight interactive IntentumDiff command shell."""
253
+ if not getattr(args, "no_banner", False) and not _banner_disabled_by_env():
254
+ _render_cli_banner(compact=False)
255
+ _console.print("[dim]Type 'help' for commands, 'exit' or 'quit' to leave.[/dim]")
256
+ from intentumdiff.cli._parser import _build_parser
257
+
258
+ parser = _build_parser()
259
+ while True:
260
+ try:
261
+ line = input("intentumdiff> ")
262
+ except EOFError:
263
+ _console.print()
264
+ return
265
+ except KeyboardInterrupt:
266
+ _console.print()
267
+ continue
268
+ if not _run_shell_line(line, parser):
269
+ return
270
+
271
+
272
+ def _write_output(text: str, output: str | None) -> None:
273
+ if output:
274
+ Path(output).write_text(text, encoding="utf-8")
275
+ else:
276
+ print(text)
277
+
278
+
279
+ def _json_default(value: object) -> str:
280
+ return str(value)
281
+
282
+
283
+ def _record_diagnostics_db(
284
+ diffs: SemanticDiff | list[SemanticDiff],
285
+ args: argparse.Namespace,
286
+ ) -> None:
287
+ db_path = getattr(args, "diagnostics_db", None)
288
+ if not db_path:
289
+ return
290
+ from intentumdiff.cache.duckdb_store import DuckDBAnalyticsStore
291
+
292
+ items = diffs if isinstance(diffs, list) else [diffs]
293
+ with DuckDBAnalyticsStore(db_path) as store:
294
+ store.record_diagnostics_run(
295
+ [item.model_dump() for item in items],
296
+ command=getattr(args, "command", ""),
297
+ repo=str(getattr(args, "repo", "")),
298
+ argv=getattr(args, "_argv", None),
299
+ )
300
+
301
+
302
+ def _render_terminal(diff: SemanticDiff) -> None:
303
+ if diff.guardrail_violations:
304
+ guardrail_table = Table(
305
+ title="Protected semantic changes",
306
+ title_style="bold red",
307
+ box=box.SIMPLE_HEAVY,
308
+ border_style="red",
309
+ )
310
+ guardrail_table.add_column("Severity", style="bold", no_wrap=True)
311
+ guardrail_table.add_column("Location", style="cyan")
312
+ guardrail_table.add_column("Message")
313
+ guardrail_table.add_column("Value", style="dim")
314
+ for violation in diff.guardrail_violations:
315
+ color = "red" if violation.severity == GuardrailSeverity.IMMUTABLE else "yellow"
316
+ old_new = ""
317
+ if violation.old_value or violation.new_value:
318
+ old_new = f"{violation.old_value!r} -> {violation.new_value!r}"
319
+ guardrail_table.add_row(
320
+ f"[{color}]{violation.severity.value.upper()}[/{color}]",
321
+ f"{violation.file}::{violation.semantic_path}",
322
+ violation.message,
323
+ old_new,
324
+ )
325
+ _console.print(guardrail_table)
326
+ _console.print()
327
+
328
+ if not diff.has_semantic_changes:
329
+ state_style = "green"
330
+ state_title = "No changes detected"
331
+ state_message = "IntentumDiff found no semantic differences."
332
+ if diff.is_style_only:
333
+ state_style = "yellow"
334
+ state_title = "Style-only change"
335
+ state_message = "Formatting changed, but no semantic differences were found."
336
+ elif diff.is_fallback:
337
+ state_style = "yellow"
338
+ state_title = "Token fallback used"
339
+ state_message = "Parse errors were detected, so IntentumDiff used token-level fallback."
340
+ _console.print(
341
+ Panel(
342
+ state_message,
343
+ title=f"[bold {state_style}]{state_title}[/bold {state_style}]",
344
+ border_style=state_style,
345
+ box=box.ROUNDED,
346
+ expand=False,
347
+ )
348
+ )
349
+ return
350
+ scope_label = (diff.staging_status or "working tree").replace("_", " ")
351
+ header = Table.grid(padding=(0, 2))
352
+ header.add_column(style="bold")
353
+ header.add_column()
354
+ header.add_row("Old", diff.old_filename or "<unknown>")
355
+ header.add_row("New", diff.new_filename or "<unknown>")
356
+ header.add_row("Language", diff.language or "unknown")
357
+ header.add_row("Scope", scope_label)
358
+ header.add_row("Changes", str(len(diff.changes)))
359
+ _console.print(
360
+ Panel(
361
+ header,
362
+ title="[bold cyan]Semantic diff[/bold cyan]",
363
+ border_style="cyan",
364
+ box=box.ROUNDED,
365
+ expand=False,
366
+ )
367
+ )
368
+ _console.print()
369
+
370
+ changes_table = Table(
371
+ box=box.SIMPLE,
372
+ border_style="dim",
373
+ header_style="bold",
374
+ show_header=True,
375
+ )
376
+ changes_table.add_column("Type", no_wrap=True)
377
+ changes_table.add_column("Description", overflow="fold")
378
+ for change in diff.changes:
379
+ from intentumdiff.core.models import ChangeType
380
+ ct = (
381
+ change.change_type.value
382
+ if isinstance(change.change_type, ChangeType)
383
+ else str(change.change_type)
384
+ )
385
+ color_map = {
386
+ "ADDITION": "green",
387
+ "DELETION": "red",
388
+ "MODIFICATION": "yellow",
389
+ "MOVE": "cyan",
390
+ "REFACTORING": "magenta",
391
+ "STYLE_ONLY": "dim",
392
+ }
393
+ color = color_map.get(ct, "white")
394
+ changes_table.add_row(f"[{color}]{ct}[/{color}]", change.description)
395
+ _console.print(changes_table)
396
+ return
397
+
398
+ def _render(diff: SemanticDiff, fmt: str, output: str | None, fuel: int | None = None) -> None:
399
+ if fmt == "terminal" and not output:
400
+ _render_terminal(diff)
401
+ return
402
+
403
+ if fmt == "terminal":
404
+ # Render to plain text file (no ANSI)
405
+ with open(output, "w", encoding="utf-8") as fh:
406
+ plain = Console(file=fh, highlight=False)
407
+ plain.print(
408
+ f"Semantic diff: {diff.old_filename} -> "
409
+ f"{diff.new_filename} ({diff.language})"
410
+ )
411
+ for violation in diff.guardrail_violations:
412
+ plain.print(
413
+ f" GUARDRAIL {violation.severity.value.upper()} "
414
+ f"{violation.file}::{violation.semantic_path} {violation.message}"
415
+ )
416
+ for change in diff.changes:
417
+ plain.print(f" {change.change_type.value:14} {change.description}")
418
+ return
419
+
420
+ if fmt == "json":
421
+ _write_output(diff.model_dump_json(indent=2), output)
422
+ return
423
+
424
+ # For patch / html / llm — delegate to the matching Wasm renderer plugin
425
+ from intentumdiff.plugins.loader import load_plugin
426
+
427
+ wasm_dir = Path(__file__).parent / "wasm"
428
+ candidates = list(wasm_dir.glob(f"{fmt.replace('-', '_')}_renderer.wasm"))
429
+ if not candidates:
430
+ # Fallback: scan for any renderer plugin that reports this format name
431
+ for p in sorted(wasm_dir.glob("*_renderer.wasm")):
432
+ with suppress(Exception):
433
+ pl = load_plugin(p)
434
+ if pl.call_format_name() == fmt:
435
+ candidates = [p]
436
+ break
437
+
438
+ if not candidates:
439
+ _err.print(f"[red]No renderer plugin found for format '{fmt}'.[/red]")
440
+ sys.exit(1)
441
+
442
+ try:
443
+ diff_json = diff.model_dump_json()
444
+ plugin_fuel = fuel if fuel is not None else 100_000_000
445
+ adaptive_fuel = max(plugin_fuel, 20_000_000 + len(diff_json) * 100)
446
+ pl = load_plugin(candidates[0], adaptive_fuel)
447
+ result = pl.call_render(diff_json)
448
+ _write_output(result, output)
449
+ except Exception as exc:
450
+ _err.print(f"[red]Renderer error: {exc}[/red]")
451
+ sys.exit(1)
452
+
453
+
454
+ def _emit_phase_profiles(
455
+ diffs: SemanticDiff | list[SemanticDiff],
456
+ *,
457
+ render_ms: float | None = None,
458
+ ) -> None:
459
+ items = diffs if isinstance(diffs, list) else [diffs]
460
+ files: list[dict[str, Any]] = []
461
+ for diff in items:
462
+ phase_timings = diff.metadata.get("phase_timings")
463
+ if phase_timings:
464
+ files.append(
465
+ {
466
+ "old_filename": diff.old_filename,
467
+ "new_filename": diff.new_filename,
468
+ "language": diff.language,
469
+ "phase_timings": phase_timings,
470
+ }
471
+ )
472
+ if not files:
473
+ return
474
+ payload: dict[str, Any] = {"phase_profiles": files}
475
+ if render_ms is not None:
476
+ payload["cli_render_ms"] = round(render_ms, 3)
477
+ print(json.dumps(payload, separators=(",", ":")), file=sys.stderr)
478
+
479
+
480
+ def _render_with_profile(
481
+ diff: SemanticDiff,
482
+ args: argparse.Namespace,
483
+ *,
484
+ fuel: int | None = None,
485
+ ) -> None:
486
+ started = time.perf_counter()
487
+ _render(diff, args.format, args.output, fuel=fuel)
488
+ _emit_phase_profiles(diff, render_ms=(time.perf_counter() - started) * 1000)
489
+
490
+
491
+ def _has_immutable_guardrail(diff: SemanticDiff) -> bool:
492
+ return any(
493
+ violation.severity == GuardrailSeverity.IMMUTABLE
494
+ for violation in diff.guardrail_violations
495
+ )
496
+
497
+
498
+ def _exit_if_guardrails_strict(diffs: SemanticDiff | list[SemanticDiff], strict: bool) -> None:
499
+ result = _guardrail_result(diffs, strict=strict)
500
+ _exit_if_guardrail_result_fails(result)
501
+
502
+
503
+ def _guardrail_result(
504
+ diffs: SemanticDiff | list[SemanticDiff],
505
+ *,
506
+ strict: bool,
507
+ checked_files: int | None = None,
508
+ ) -> GuardrailCheckResult:
509
+ return guardrail_result_from_diffs(
510
+ diffs,
511
+ strict=strict,
512
+ checked_files=checked_files,
513
+ )
514
+
515
+
516
+ def _emit_guardrail_reports(
517
+ diffs: SemanticDiff | list[SemanticDiff],
518
+ args: argparse.Namespace,
519
+ *,
520
+ checked_files: int | None = None,
521
+ ) -> GuardrailCheckResult:
522
+ result = _guardrail_result(
523
+ diffs,
524
+ strict=getattr(args, "guardrails_strict", False),
525
+ checked_files=checked_files,
526
+ )
527
+ if getattr(args, "guardrails_annotations", "none") == "github":
528
+ annotations = render_guardrail_annotations(result)
529
+ if annotations:
530
+ print(annotations)
531
+
532
+ json_output = getattr(args, "guardrails_json", None)
533
+ if json_output:
534
+ _write_output(render_guardrail_json(result), json_output)
535
+
536
+ sarif_output = getattr(args, "guardrails_sarif", None)
537
+ if sarif_output:
538
+ _write_output(render_guardrail_sarif(result), sarif_output)
539
+
540
+ return result
541
+
542
+
543
+ def _exit_if_guardrail_result_fails(result: GuardrailCheckResult) -> None:
544
+ if result.passed:
545
+ return
546
+ _err.print("[bold red]Immutable semantic guardrail violation detected.[/bold red]")
547
+ sys.exit(2)
548
+
549
+
550
+ def _resolve_repo_root(start_path: str | Path) -> Path:
551
+ """Resolve the git repository root for editor/live-server commands."""
552
+ from intentumdiff.vcs.git_cli import NotAGitRepositoryError, resolve_repo_root
553
+
554
+ start = Path(start_path)
555
+ with suppress(NotAGitRepositoryError):
556
+ return Path(resolve_repo_root(start)).resolve()
557
+ return (start if start.is_dir() else start.parent).resolve()
558
+
559
+
560
+ # ---------------------------------------------------------------------------
561
+ # Sub-command handlers
562
+ # ---------------------------------------------------------------------------
563
+
564
+
565
+ def _asset_options_from_args(args: argparse.Namespace) -> Any:
566
+ return {
567
+ "dimension_policy": args.dimension_policy,
568
+ "pixel_threshold": args.pixel_threshold,
569
+ "region_min_area": args.region_min_area,
570
+ "alpha_handling": args.alpha_handling,
571
+ "max_decoded_pixels": args.max_decoded_pixels,
572
+ "file_path": getattr(args, "file_path", None),
573
+ }
574
+
575
+
576
+ def _print_asset_result(result: dict[str, Any]) -> None:
577
+ _console.print(f"[bold cyan]{result.get('summary', 'Asset diff complete.')}[/bold cyan]")
578
+ artifacts = result.get("artifacts") or {}
579
+ if artifacts:
580
+ for name, path in artifacts.items():
581
+ _console.print(f" [dim]{name}[/dim] {path}")
582
+ warnings = result.get("warnings") or []
583
+ for warning in warnings:
584
+ _console.print(f" [yellow]Warning:[/yellow] {warning}")
585
+ decoded_cost = result.get("decoded_cost") or {}
586
+ if decoded_cost:
587
+ before_pixels = decoded_cost.get("before_pixels")
588
+ after_pixels = decoded_cost.get("after_pixels")
589
+ max_pixels = decoded_cost.get("max_decoded_pixels")
590
+ _console.print(
591
+ " [dim]Decoded image cost:[/dim] "
592
+ f"before={before_pixels} px after={after_pixels} px limit={max_pixels} px"
593
+ )
594
+
595
+
596
+ def _emit_asset_payload(payload: dict[str, Any], *, json_output: bool) -> None:
597
+ if json_output:
598
+ print(json.dumps(payload, indent=2, sort_keys=True))
599
+ return
600
+ if payload.get("kind") == "asset_diff_batch":
601
+ diffs = payload.get("asset_diffs") or []
602
+ skipped = payload.get("skipped") or []
603
+ if not diffs and not skipped:
604
+ _console.print("[green]No changed image assets found.[/green]")
605
+ return
606
+ for item in diffs:
607
+ path = item.get("file_path") or "<asset>"
608
+ _console.rule(path)
609
+ _print_asset_result(item)
610
+ for item in skipped:
611
+ _console.print(
612
+ f"[yellow]Skipped:[/yellow] {item.get('file_path', '<asset>')} "
613
+ f"({item.get('reason', 'no comparable image pair')})"
614
+ )
615
+ return
616
+ _print_asset_result(payload)
617
+
618
+
619
+ def _parse_fuel(value: str) -> int:
620
+ """argparse ``type=`` for --fuel: accepts integers or 'inf'/'infinite'/-1."""
621
+ if value.strip().lower() in ("inf", "infinite", "unlimited"):
622
+ return -1
623
+ try:
624
+ n = int(value)
625
+ except ValueError as exc:
626
+ raise argparse.ArgumentTypeError(
627
+ f"invalid fuel value {value!r}: use a positive integer, -1, 'inf', or 'infinite'"
628
+ ) from exc
629
+ if n == -1:
630
+ return -1
631
+ if n < 1:
632
+ raise argparse.ArgumentTypeError(
633
+ f"fuel must be a positive integer (or -1 / 'inf' for unlimited), got {n}"
634
+ )
635
+ return n
636
+
637
+
638
+ def _warn_if_unlimited_fuel(fuel: int | None) -> None:
639
+ """Print a visible warning if the user opted into unlimited fuel."""
640
+ if fuel == -1:
641
+ _err.print(
642
+ "[yellow]Warning: unlimited Wasm fuel — plugins are uncapped and may "
643
+ "run indefinitely on malformed input.[/yellow]"
644
+ )
@@ -0,0 +1,59 @@
1
+ """Content-type detection via the Rust core (magic-byte sniffing).
2
+
3
+ Thin Python bridge over the Rust ``detect_content_type_json`` entry point. Used
4
+ to route changed files — text goes to the semantic parser, binary/image assets
5
+ go to the perceptual asset diff — and to enrich diff metadata with the detected
6
+ MIME type. Detection inspects the leading bytes of a file, not its extension.
7
+
8
+ Falls back to a NUL-byte heuristic if the Rust core is unavailable, so callers
9
+ never crash when the native extension is missing.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from typing import Any, TypedDict
16
+
17
+ #: How many leading bytes to sniff. A few KB is plenty for magic-byte detection.
18
+ HEAD_BYTES = 8192
19
+
20
+
21
+ class ContentType(TypedDict):
22
+ mime: str
23
+ extension: str
24
+ category: str
25
+ is_text: bool
26
+
27
+
28
+ def _fallback(head: bytes) -> ContentType:
29
+ is_text = b"\x00" not in head[:HEAD_BYTES]
30
+ return {
31
+ "mime": "text/plain" if is_text else "application/octet-stream",
32
+ "extension": "",
33
+ "category": "text" if is_text else "binary",
34
+ "is_text": is_text,
35
+ }
36
+
37
+
38
+ def detect_content_type(head: bytes) -> ContentType:
39
+ """Return the detected content type for a file's leading bytes."""
40
+ sample = bytes(head[:HEAD_BYTES])
41
+ try:
42
+ from intentumdiff.rust_core import _load_backend
43
+
44
+ backend = _load_backend()
45
+ raw = backend.detect_content_type_json(sample)
46
+ parsed: dict[str, Any] = json.loads(raw)
47
+ return {
48
+ "mime": str(parsed.get("mime", "application/octet-stream")),
49
+ "extension": str(parsed.get("extension", "")),
50
+ "category": str(parsed.get("category", "binary")),
51
+ "is_text": bool(parsed.get("is_text", False)),
52
+ }
53
+ except Exception: # noqa: BLE001 — detection must never break the diff pipeline.
54
+ return _fallback(sample)
55
+
56
+
57
+ def is_text_bytes(head: bytes) -> bool:
58
+ """Whether *head* should be sent to the semantic text engine."""
59
+ return detect_content_type(head)["is_text"]
@@ -0,0 +1 @@
1
+ # intentumdiff/core