intentumdiff-python 0.0.1__py3-none-win_arm64.whl → 0.0.3b1__py3-none-win_arm64.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
@@ -12,59 +12,25 @@ from intentumdiff.analysis.diagnostics import (
12
12
  DiagnosticsRecorder,
13
13
  )
14
14
  from intentumdiff.core.models import (
15
- ChangeGroupKind,
16
15
  SemanticDiff,
17
16
  )
18
17
 
19
18
  logger = logging.getLogger(__name__)
20
19
 
21
- _ADDED_FILE_STATUSES = frozenset({"added", "add", "a", "new", "untracked"})
22
- _DELETED_FILE_STATUSES = frozenset({"deleted", "delete", "d", "removed", "remove"})
20
+ def _infer_file_lifecycle(old_source: str, new_source: str, staging_status: str | None = None) -> str:
21
+ """Adapt source/status facts to the shared Rust lifecycle policy."""
22
+ from intentumdiff.rust_core import _c_abi_call
23
+ return _c_abi_call("infer_file_lifecycle", old_source, new_source, staging_status)
23
24
 
24
25
 
25
- def _infer_file_lifecycle(
26
- old_source: str,
27
- new_source: str,
28
- staging_status: str | None = None,
29
- ) -> str:
30
- """Infer the file lifecycle from source presence and git status facts.
26
+ def _apply_file_lifecycle_to_diff(diff: SemanticDiff, lifecycle: str) -> SemanticDiff:
27
+ """Convert the shared Rust result back into the public Python DTO."""
28
+ from intentumdiff.rust_core import _c_abi_call, _require_complete_batch_diff_dto
31
29
 
32
- This is shell-owned source metadata, not semantic classification. The engine
33
- still owns the raw additions/deletions and review groups.
34
- """
35
-
36
- status = (staging_status or "").strip().lower()
37
- if status in _ADDED_FILE_STATUSES:
38
- return "added"
39
- if status in _DELETED_FILE_STATUSES:
40
- return "deleted"
41
- if old_source == "" and new_source != "":
42
- return "added"
43
- if old_source != "" and new_source == "":
44
- return "deleted"
45
- return "modified"
46
-
47
-
48
- def _apply_file_lifecycle_to_diff(
49
- diff: SemanticDiff,
50
- lifecycle: str,
51
- ) -> SemanticDiff:
52
- metadata = dict(diff.metadata)
53
- metadata["file_lifecycle"] = lifecycle
54
- if lifecycle == "modified":
55
- return diff.model_copy(update={"metadata": metadata})
56
-
57
- change_groups = [
58
- group for group in diff.change_groups if group.kind != ChangeGroupKind.IGNORED_STYLE
59
- ]
60
- return diff.model_copy(
61
- update={
62
- "metadata": metadata,
63
- "change_groups": change_groups,
64
- "is_style_only": False,
65
- "has_semantic_changes": bool(diff.changes),
66
- }
30
+ response = _c_abi_call(
31
+ "finalize_file_lifecycle", diff.model_dump(mode="json"), lifecycle,
67
32
  )
33
+ return SemanticDiff.model_validate(_require_complete_batch_diff_dto(response))
68
34
 
69
35
 
70
36
  class _PhaseProfiler:
@@ -106,8 +72,6 @@ class _PhaseProfiler:
106
72
  }
107
73
 
108
74
 
109
- _DEFAULT_PLUGIN_FUEL = 100_000_000
110
- _EXPLICIT_FUEL_EXHAUSTION_TEST_CAP = 1_000_000
111
75
  # Hotspot thresholds are calibrated to the measured worst legitimate parser plus ~30%
112
76
  # headroom. Two effects moved the floor in 2026-07: literal-container text capture in the
113
77
  # tree-sitter converters (issue #46 — a deliberate correctness cost), and whole-binary LTO
@@ -126,32 +90,17 @@ def _attach_content_type_metadata(
126
90
  """Enrich a diff's metadata with the detected content type (mime + category).
127
91
 
128
92
  Uses the Rust magic-byte detector on the changed content so downstream
129
- surfaces can show what kind of file was diffed. Never raises — the detector
130
- bridge falls back gracefully when the native core is unavailable.
93
+ surfaces can show what kind of file was diffed. Malformed UTF-8 source
94
+ and required Rust detector failures propagate; no fabricated bytes/fallback.
131
95
  """
132
96
  from intentumdiff.content_type import detect_content_type
133
97
 
134
- head = (new_content or old_content)[:8192].encode("utf-8", errors="replace")
98
+ head = (new_content or old_content)[:8192].encode("utf-8", errors="strict")
135
99
  metadata = dict(diff.metadata or {})
136
100
  metadata["content_type"] = detect_content_type(head)
137
101
  return diff.model_copy(update={"metadata": metadata})
138
102
 
139
103
 
140
- def _fuel_budget(base: int, extra: int) -> int:
141
- """Return an adaptive budget without hiding explicit low-fuel tests.
142
-
143
- Real editor/CLI fuel settings are a floor, not a guarantee that ordinary
144
- source files will fail once they cross that exact number. Tiny budgets are
145
- still respected so fuel-pressure tests can prove runaway plugins fail
146
- explicitly instead of being silently promoted to a larger cap.
147
- """
148
- if base == -1:
149
- return base
150
- if base < _EXPLICIT_FUEL_EXHAUSTION_TEST_CAP:
151
- return base
152
- return max(base, extra)
153
-
154
-
155
104
  def _drain_plugin_telemetry(plugin_adapter: Any) -> list[dict[str, Any]]:
156
105
  drain = getattr(plugin_adapter, "drain_telemetry", None)
157
106
  if not callable(drain):
@@ -1,151 +1,36 @@
1
- """Compile database metadata for C/C++ review context."""
2
-
1
+ """Filesystem adapter for the shared Rust compile-context API."""
3
2
  from __future__ import annotations
4
-
5
- import hashlib
6
3
  import json
7
- import shlex
8
4
  from pathlib import Path
9
5
  from typing import Any
10
6
 
11
- _CXX_LANGUAGES = frozenset({"c", "cpp", "c++", "cxx"})
12
- _COMPILE_DATABASE = "compile_commands.json"
13
-
14
7
 
15
- def compile_commands_metadata(
16
- *,
17
- filename: str,
18
- language: str,
19
- cwd: Path | None = None,
20
- ) -> dict[str, Any] | None:
21
- """Return normalized compile-command context for a C/C++ file if available."""
22
-
23
- if language.lower() not in _CXX_LANGUAGES:
24
- return None
25
- logical_path = Path(filename)
26
- if str(logical_path).startswith("<"):
8
+ def compile_commands_metadata(*, filename: str, language: str, cwd: Path | None = None) -> dict[str, Any] | None:
9
+ from intentumdiff.rust_core import _c_abi_call
10
+ if language.lower() not in {"c", "cpp", "c++", "cxx"} or filename.startswith("<"):
27
11
  return None
28
- base_dir = cwd or Path.cwd()
29
- file_path = logical_path if logical_path.is_absolute() else base_dir / logical_path
30
- database = _find_compile_database(file_path)
31
- if database is None:
32
- return None
33
- entry = _matching_entry(database, file_path)
34
- if entry is None:
35
- return None
36
- arguments = _entry_arguments(entry)
37
- if not arguments:
38
- return None
39
- metadata = {
40
- "database": _repo_relative(database, base_dir),
41
- "file": _repo_relative(_entry_file_path(entry, database.parent), base_dir),
42
- "directory": _repo_relative(Path(str(entry.get("directory") or database.parent)), base_dir),
43
- "arguments": arguments,
44
- "defines": _flag_values(arguments, "-D"),
45
- "include_dirs": _include_dirs(arguments),
46
- "standard": _standard(arguments),
47
- }
48
- metadata["fingerprint"] = _fingerprint(metadata)
49
- return metadata
50
-
51
-
52
- def _find_compile_database(file_path: Path) -> Path | None:
53
- for directory in [file_path.parent, *file_path.parents]:
54
- candidate = directory / _COMPILE_DATABASE
55
- if candidate.is_file():
56
- return candidate
57
- return None
58
-
59
-
60
- def _matching_entry(database: Path, file_path: Path) -> dict[str, Any] | None:
61
- try:
62
- raw = json.loads(database.read_text(encoding="utf8"))
63
- except (OSError, json.JSONDecodeError):
64
- return None
65
- if not isinstance(raw, list):
66
- return None
67
- target = _normalized_path(file_path)
68
- basename = file_path.name.lower()
69
- basename_match: dict[str, Any] | None = None
70
- for item in raw:
71
- if not isinstance(item, dict):
72
- continue
73
- entry_file = _entry_file_path(item, database.parent)
74
- if _normalized_path(entry_file) == target:
75
- return item
76
- if entry_file.name.lower() == basename and basename_match is None:
77
- basename_match = item
78
- return basename_match
79
-
80
-
81
- def _entry_file_path(entry: dict[str, Any], database_dir: Path) -> Path:
82
- raw_file = Path(str(entry.get("file") or ""))
83
- directory = Path(str(entry.get("directory") or database_dir))
84
- return raw_file if raw_file.is_absolute() else directory / raw_file
85
-
86
-
87
- def _entry_arguments(entry: dict[str, Any]) -> list[str]:
88
- arguments = entry.get("arguments")
89
- if isinstance(arguments, list):
90
- return [str(arg) for arg in arguments if str(arg)]
91
- command = entry.get("command")
92
- if isinstance(command, str) and command.strip():
12
+ base_dir = (cwd or Path.cwd()).resolve()
13
+ file_path = Path(filename)
14
+ if not file_path.is_absolute():
15
+ file_path = base_dir / file_path
16
+ for directory in (file_path.parent, *file_path.parents):
17
+ database = directory / "compile_commands.json"
93
18
  try:
94
- return shlex.split(command, posix=False)
95
- except ValueError:
96
- return command.split()
97
- return []
98
-
99
-
100
- def _flag_values(arguments: list[str], prefix: str) -> list[str]:
101
- values: list[str] = []
102
- index = 0
103
- while index < len(arguments):
104
- arg = arguments[index]
105
- if arg == prefix and index + 1 < len(arguments):
106
- values.append(arguments[index + 1])
107
- index += 2
19
+ raw = database.read_text(encoding="utf-8")
20
+ except FileNotFoundError as exc:
21
+ # A broken link represents an explicitly configured unusable DB,
22
+ # not an absent optional compile database.
23
+ if database.is_symlink():
24
+ raise RuntimeError(f"Cannot read configured compile database {database}: {exc}") from exc
108
25
  continue
109
- if arg.startswith(prefix) and len(arg) > len(prefix):
110
- values.append(arg[len(prefix):])
111
- index += 1
112
- return values
113
-
114
-
115
- def _include_dirs(arguments: list[str]) -> list[str]:
116
- values = _flag_values(arguments, "-I")
117
- values.extend(_flag_values(arguments, "/I"))
118
- return values
119
-
120
-
121
- def _standard(arguments: list[str]) -> str | None:
122
- for arg in arguments:
123
- if arg.startswith("-std="):
124
- return arg.removeprefix("-std=")
125
- if arg.startswith("/std:"):
126
- return arg.removeprefix("/std:")
26
+ except (OSError, UnicodeError) as exc:
27
+ raise RuntimeError(f"Cannot read configured compile database {database}: {exc}") from exc
28
+ try:
29
+ contents = json.loads(raw)
30
+ except json.JSONDecodeError as exc:
31
+ raise ValueError(f"Malformed compile database {database}: {exc}") from exc
32
+ return _c_abi_call("compile_context", json.dumps({
33
+ "database": contents, "database_path": str(database), "filename": filename,
34
+ "language": language, "cwd": str(base_dir),
35
+ }))
127
36
  return None
128
-
129
-
130
- def _fingerprint(metadata: dict[str, Any]) -> str:
131
- payload = {
132
- key: metadata[key]
133
- for key in ("file", "arguments", "defines", "include_dirs", "standard")
134
- if metadata.get(key)
135
- }
136
- encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf8")
137
- return hashlib.sha256(encoded).hexdigest()[:16]
138
-
139
-
140
- def _normalized_path(path: Path) -> str:
141
- try:
142
- return str(path.resolve()).replace("\\", "/").lower()
143
- except OSError:
144
- return str(path.absolute()).replace("\\", "/").lower()
145
-
146
-
147
- def _repo_relative(path: Path, base_dir: Path) -> str:
148
- try:
149
- return path.resolve().relative_to(base_dir.resolve()).as_posix()
150
- except (OSError, ValueError):
151
- return path.as_posix()
@@ -32,8 +32,8 @@ def detect_cross_file_changes(
32
32
 
33
33
  Both indices must have had ``build()`` called first. The comparison itself
34
34
  is performed by the Rust core over the flat symbol tables; this function only
35
- marshals the tables in and the change list back out. Returns an empty list
36
- when the core is unavailable.
35
+ marshals the tables in and the change list back out. Raises when the core is unavailable or fails; an empty list means
36
+ the engine successfully found no cross-file changes.
37
37
  """
38
38
  from intentumdiff.rust_core import try_rust_diff_symbol_tables
39
39
 
@@ -45,27 +45,25 @@ def detect_cross_file_changes(
45
45
  )
46
46
 
47
47
  result = try_rust_diff_symbol_tables(old_json, new_json)
48
- if result is None:
49
- return []
50
48
 
51
- changes: list[CrossFileChange] = []
52
- for item in result:
53
- changes.append(
54
- CrossFileChange(
55
- change_type=ChangeType(item["change_type"]),
56
- symbol_name=item["symbol_name"],
57
- old_file=item["old_file"],
58
- new_file=item["new_file"],
59
- old_node_id=item.get("old_node_id"),
60
- new_node_id=item.get("new_node_id"),
61
- old_position=item.get("old_position"),
62
- new_position=item.get("new_position"),
63
- old_language=item.get("old_language", ""),
64
- new_language=item.get("new_language", ""),
65
- node_type=item.get("node_type", ""),
66
- symbol_kind=item.get("symbol_kind", ""),
67
- confidence=item.get("confidence", 1.0),
68
- description=item.get("description", ""),
69
- )
70
- )
71
- return changes
49
+ return [cross_file_change_from_core(item) for item in result]
50
+
51
+
52
+ def cross_file_change_from_core(item: dict) -> CrossFileChange:
53
+ """DTO mapping for one core cross-file change."""
54
+ return CrossFileChange(
55
+ change_type=ChangeType(item["change_type"]),
56
+ symbol_name=item["symbol_name"],
57
+ old_file=item["old_file"],
58
+ new_file=item["new_file"],
59
+ old_node_id=item.get("old_node_id"),
60
+ new_node_id=item.get("new_node_id"),
61
+ old_position=item.get("old_position"),
62
+ new_position=item.get("new_position"),
63
+ old_language=item.get("old_language", ""),
64
+ new_language=item.get("new_language", ""),
65
+ node_type=item.get("node_type", ""),
66
+ symbol_kind=item.get("symbol_kind", ""),
67
+ confidence=item.get("confidence", 1.0),
68
+ description=item.get("description", ""),
69
+ )
@@ -6,14 +6,10 @@ from collections.abc import Mapping, Sequence
6
6
  from dataclasses import dataclass, field
7
7
  from typing import Any
8
8
 
9
- from intentumdiff.core.models import Change, ChangeGroup, ChangeType, SemanticNode
9
+ from intentumdiff.core.models import ChangeGroup, SemanticNode
10
10
 
11
11
 
12
12
  DIAGNOSTICS_VERSION = 2
13
- _PAIR_SAMPLE_LIMIT = 8
14
- _CANDIDATE_SAMPLE_LIMIT = 8
15
-
16
-
17
13
  @dataclass
18
14
  class DiagnosticsRecorder:
19
15
  """Collect JSON-safe diagnostics events when enabled."""
@@ -101,40 +97,6 @@ class DiagnosticsRecorder:
101
97
  metadata=payload,
102
98
  )
103
99
 
104
- def record_candidate_summary(
105
- self,
106
- *,
107
- stage: str,
108
- rule_id: str,
109
- action: str = "candidate_summary",
110
- reason: str = "",
111
- evaluated_count: int = 0,
112
- accepted_count: int = 0,
113
- rejected_count: int = 0,
114
- rejection_reasons: Mapping[str, int] | None = None,
115
- accepted_samples: Sequence[Mapping[str, Any]] = (),
116
- rejected_samples: Sequence[Mapping[str, Any]] = (),
117
- metadata: Mapping[str, Any] | None = None,
118
- ) -> None:
119
- """Record bounded accepted/rejected candidate evidence."""
120
-
121
- payload = {
122
- "evaluated_count": evaluated_count,
123
- "accepted_count": accepted_count,
124
- "rejected_count": rejected_count,
125
- "rejection_reasons": dict(rejection_reasons or {}),
126
- "accepted_samples": list(accepted_samples[:_CANDIDATE_SAMPLE_LIMIT]),
127
- "rejected_samples": list(rejected_samples[:_CANDIDATE_SAMPLE_LIMIT]),
128
- **dict(metadata or {}),
129
- }
130
- self.record(
131
- stage=stage,
132
- action=action,
133
- rule_id=rule_id,
134
- reason=reason,
135
- metadata=payload,
136
- )
137
-
138
100
  def record_group(self, *, stage: str, group: ChangeGroup) -> None:
139
101
  kind = group.kind.value if hasattr(group.kind, "value") else str(group.kind)
140
102
  self.record(
@@ -158,39 +120,6 @@ class DiagnosticsRecorder:
158
120
  },
159
121
  )
160
122
 
161
- def record_change(
162
- self,
163
- *,
164
- stage: str,
165
- change: Change,
166
- action: str = "change",
167
- rule_id: str = "",
168
- reason: str = "",
169
- ) -> None:
170
- change_type = (
171
- change.change_type.value
172
- if isinstance(change.change_type, ChangeType)
173
- else str(change.change_type)
174
- )
175
- self.record(
176
- stage=stage,
177
- action=action,
178
- rule_id=rule_id,
179
- reason=reason,
180
- old_nodes=[change.old_node],
181
- new_nodes=[change.new_node],
182
- confidence=change.confidence,
183
- metadata={
184
- "change_type": change_type,
185
- "description": change.description,
186
- "refactoring_kind": (
187
- change.refactoring_kind.value
188
- if change.refactoring_kind is not None
189
- else None
190
- ),
191
- },
192
- )
193
-
194
123
  def snapshot(self) -> dict[str, Any]:
195
124
  return {
196
125
  "version": DIAGNOSTICS_VERSION,
@@ -200,98 +129,6 @@ class DiagnosticsRecorder:
200
129
  }
201
130
 
202
131
 
203
- def record_matching_delta(
204
- recorder: DiagnosticsRecorder,
205
- *,
206
- stage: str,
207
- rule_id: str,
208
- before: Sequence[Any],
209
- after: Sequence[Any],
210
- ) -> None:
211
- """Record before/after matching counts and sampled pair changes."""
212
-
213
- if not recorder.enabled:
214
- return
215
-
216
- before_pairs = {_pair_key(match): match for match in before}
217
- after_pairs = {_pair_key(match): match for match in after}
218
- added = [after_pairs[key] for key in after_pairs.keys() - before_pairs.keys()]
219
- removed = [before_pairs[key] for key in before_pairs.keys() - after_pairs.keys()]
220
- if not added and not removed and len(before_pairs) == len(after_pairs):
221
- recorder.record(
222
- stage=stage,
223
- action="augment_matching",
224
- rule_id=rule_id,
225
- reason="no matching changes",
226
- metadata={"before_pairs": len(before_pairs), "after_pairs": len(after_pairs)},
227
- )
228
- return
229
-
230
- recorder.record(
231
- stage=stage,
232
- action="augment_matching",
233
- rule_id=rule_id,
234
- reason="matching augmentation applied",
235
- metadata={
236
- "before_pairs": len(before_pairs),
237
- "after_pairs": len(after_pairs),
238
- "added_pair_count": len(added),
239
- "removed_pair_count": len(removed),
240
- "added_pairs": [_pair_digest(match) for match in added[:_PAIR_SAMPLE_LIMIT]],
241
- "removed_pairs": [
242
- _pair_digest(match) for match in removed[:_PAIR_SAMPLE_LIMIT]
243
- ],
244
- },
245
- )
246
-
247
-
248
- def _pair_key(match: Any) -> tuple[str, str]:
249
- return (match.old_node.id, match.new_node.id)
250
-
251
-
252
- def _pair_digest(match: Any) -> dict[str, Any]:
253
- return {
254
- "old_id": match.old_node.id,
255
- "new_id": match.new_node.id,
256
- "old_type": match.old_node.node_type,
257
- "new_type": match.new_node.node_type,
258
- "old_label": match.old_node.label,
259
- "new_label": match.new_node.label,
260
- }
261
-
262
-
263
- def node_digest(node: SemanticNode | None) -> dict[str, Any]:
264
- """Return a small diagnostics-safe node reference."""
265
-
266
- if node is None:
267
- return {}
268
- return {
269
- "id": node.id,
270
- "type": node.node_type,
271
- "label": node.label,
272
- }
273
-
274
-
275
- def pair_digest(
276
- old_node: SemanticNode | None,
277
- new_node: SemanticNode | None,
278
- *,
279
- score: float | None = None,
280
- reason: str = "",
281
- ) -> dict[str, Any]:
282
- """Return a small diagnostics-safe old/new candidate reference."""
283
-
284
- payload: dict[str, Any] = {
285
- "old": node_digest(old_node),
286
- "new": node_digest(new_node),
287
- }
288
- if score is not None:
289
- payload["score"] = round(score, 4)
290
- if reason:
291
- payload["reason"] = reason
292
- return payload
293
-
294
-
295
132
  def _json_safe(value: Any, *, depth: int = 0) -> Any:
296
133
  if depth > 6:
297
134
  return str(value)
@@ -22,25 +22,10 @@ def build_guardrail_check_result(
22
22
  strict: bool,
23
23
  metadata: Mapping[str, Any] | None = None,
24
24
  ) -> GuardrailCheckResult:
25
- """Build a counted, JSON-safe guardrail check result."""
25
+ """Core's guardrail check verdict for a list of violations (``guardrail_check_result``)."""
26
26
 
27
- items = list(violations)
28
- immutable_count = sum(
29
- violation.severity == GuardrailSeverity.IMMUTABLE for violation in items
30
- )
31
- important_count = sum(
32
- violation.severity == GuardrailSeverity.IMPORTANT for violation in items
33
- )
34
- return GuardrailCheckResult(
35
- violations=items,
36
- violation_count=len(items),
37
- immutable_count=immutable_count,
38
- important_count=important_count,
39
- checked_files=checked_files,
40
- strict=strict,
41
- passed=not (strict and immutable_count),
42
- metadata=metadata or {},
43
- )
27
+ items = [violation.model_dump(mode="json") for violation in violations]
28
+ return _core_check_result({"violations": items}, strict, checked_files, metadata)
44
29
 
45
30
 
46
31
  def guardrail_result_from_diffs(
@@ -50,20 +35,31 @@ def guardrail_result_from_diffs(
50
35
  checked_files: int | None = None,
51
36
  metadata: Mapping[str, Any] | None = None,
52
37
  ) -> GuardrailCheckResult:
53
- """Collect guardrail evidence from one or more semantic diffs."""
38
+ """Core's verdict over the diffs' violations; core counts the diffs as checked files."""
54
39
 
55
40
  items = [diffs] if isinstance(diffs, SemanticDiff) else list(diffs)
56
- violations = [
57
- violation
41
+ # Core reads only each diff's ``guardrail_violations``, so only that field is marshalled.
42
+ evidence = [
43
+ {"guardrail_violations": [v.model_dump(mode="json") for v in diff.guardrail_violations]}
58
44
  for diff in items
59
- for violation in diff.guardrail_violations
60
45
  ]
61
- return build_guardrail_check_result(
62
- violations,
63
- checked_files=len(items) if checked_files is None else checked_files,
64
- strict=strict,
65
- metadata=metadata,
66
- )
46
+ return _core_check_result({"diffs": evidence}, strict, checked_files, metadata)
47
+
48
+
49
+ def _core_check_result(
50
+ evidence: dict[str, Any],
51
+ strict: bool,
52
+ checked_files: int | None,
53
+ metadata: Mapping[str, Any] | None,
54
+ ) -> GuardrailCheckResult:
55
+ # Core owns the counts and the gate (``passed = !strict || no violations``, #296); the DTO
56
+ # only validates the result and rejects counts that disagree with the violations.
57
+ from intentumdiff.rust_core import _c_abi_call # noqa: PLC0415
58
+
59
+ request = {**evidence, "strict": strict, "checked_files": checked_files,
60
+ "metadata": None if metadata is None else dict(metadata)}
61
+ result = _c_abi_call("guardrail_check_result", json.dumps(request))
62
+ return GuardrailCheckResult.model_validate(result)
67
63
 
68
64
 
69
65
  def render_guardrail_json(result: GuardrailCheckResult, *, indent: int = 2) -> str:
@@ -142,7 +138,7 @@ def sarif_from_guardrail_result(result: GuardrailCheckResult) -> dict[str, Any]:
142
138
  "driver": {
143
139
  "name": "IntentumDiff",
144
140
  "informationUri": (
145
- "https://github.com/buchochelliq-labs/intentumdiff"
141
+ "https://buchochelliq-labs.github.io/intentumdiff-docs/"
146
142
  ),
147
143
  "rules": list(rules_by_id.values()),
148
144
  }
@@ -239,11 +235,13 @@ def _sarif_location(violation: GuardrailViolation) -> dict[str, Any]:
239
235
 
240
236
 
241
237
  def _region(position: NodePosition) -> tuple[int, int, int, int]:
238
+ # Rust/C ABI positions are zero-based; SARIF and GitHub annotations are
239
+ # one-based. Clamping collapses line/column 0 and 1 into the same value.
242
240
  return (
243
- max(1, position.start_line),
244
- max(1, position.start_col),
245
- max(1, position.end_line),
246
- max(1, position.end_col),
241
+ position.start_line + 1,
242
+ position.start_col + 1,
243
+ position.end_line + 1,
244
+ position.end_col + 1,
247
245
  )
248
246
 
249
247