intentumdiff-python 0.0.1__py3-none-macosx_11_0_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 (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.dylib +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,309 @@
1
+ """Bounded opt-in diagnostics trace helpers for the diff pipeline."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+ from intentumdiff.core.models import Change, ChangeGroup, ChangeType, SemanticNode
10
+
11
+
12
+ DIAGNOSTICS_VERSION = 2
13
+ _PAIR_SAMPLE_LIMIT = 8
14
+ _CANDIDATE_SAMPLE_LIMIT = 8
15
+
16
+
17
+ @dataclass
18
+ class DiagnosticsRecorder:
19
+ """Collect JSON-safe diagnostics events when enabled."""
20
+
21
+ enabled: bool = False
22
+ max_events: int = 500
23
+ events: list[dict[str, Any]] = field(default_factory=list)
24
+ dropped_events: int = 0
25
+ summary: dict[str, Any] = field(default_factory=dict)
26
+
27
+ @classmethod
28
+ def disabled(cls) -> "DiagnosticsRecorder":
29
+ return cls(enabled=False)
30
+
31
+ def record(
32
+ self,
33
+ *,
34
+ stage: str,
35
+ action: str,
36
+ rule_id: str = "",
37
+ reason: str = "",
38
+ old_nodes: Sequence[SemanticNode | None] = (),
39
+ new_nodes: Sequence[SemanticNode | None] = (),
40
+ old_node_ids: Sequence[str] = (),
41
+ new_node_ids: Sequence[str] = (),
42
+ old_labels: Sequence[str] = (),
43
+ new_labels: Sequence[str] = (),
44
+ confidence: float | None = None,
45
+ metadata: Mapping[str, Any] | None = None,
46
+ ) -> None:
47
+ if not self.enabled:
48
+ return
49
+ if len(self.events) >= self.max_events:
50
+ self.dropped_events += 1
51
+ return
52
+
53
+ old_node_list = [node for node in old_nodes if node is not None]
54
+ new_node_list = [node for node in new_nodes if node is not None]
55
+ event_metadata = dict(metadata or {})
56
+ if old_node_list:
57
+ event_metadata.setdefault(
58
+ "old_node_types", [node.node_type for node in old_node_list]
59
+ )
60
+ if new_node_list:
61
+ event_metadata.setdefault(
62
+ "new_node_types", [node.node_type for node in new_node_list]
63
+ )
64
+
65
+ event = {
66
+ "stage": stage,
67
+ "rule_id": rule_id,
68
+ "action": action,
69
+ "reason": reason,
70
+ "old_node_ids": list(old_node_ids)
71
+ or [node.id for node in old_node_list],
72
+ "new_node_ids": list(new_node_ids)
73
+ or [node.id for node in new_node_list],
74
+ "old_labels": list(old_labels)
75
+ or [node.label for node in old_node_list if node.label],
76
+ "new_labels": list(new_labels)
77
+ or [node.label for node in new_node_list if node.label],
78
+ "confidence": confidence,
79
+ "metadata": _json_safe(event_metadata),
80
+ }
81
+ self.events.append(event)
82
+ stage_counts = self.summary.setdefault("events_by_stage", {})
83
+ stage_counts[stage] = stage_counts.get(stage, 0) + 1
84
+
85
+ def record_count(
86
+ self,
87
+ *,
88
+ stage: str,
89
+ action: str,
90
+ count: int,
91
+ rule_id: str = "",
92
+ reason: str = "",
93
+ metadata: Mapping[str, Any] | None = None,
94
+ ) -> None:
95
+ payload = {"count": count, **dict(metadata or {})}
96
+ self.record(
97
+ stage=stage,
98
+ action=action,
99
+ rule_id=rule_id,
100
+ reason=reason,
101
+ metadata=payload,
102
+ )
103
+
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
+ def record_group(self, *, stage: str, group: ChangeGroup) -> None:
139
+ kind = group.kind.value if hasattr(group.kind, "value") else str(group.kind)
140
+ self.record(
141
+ stage=stage,
142
+ action=kind.lower(),
143
+ rule_id=group.rule_id,
144
+ reason=str(group.metadata.get("reason", "")),
145
+ old_node_ids=group.old_node_ids,
146
+ new_node_ids=group.new_node_ids,
147
+ old_labels=group.old_labels,
148
+ new_labels=group.new_labels,
149
+ confidence=group.confidence,
150
+ metadata={
151
+ "raw_change_indices": group.raw_change_indices,
152
+ "refactoring_kind": (
153
+ group.refactoring_kind.value
154
+ if group.refactoring_kind is not None
155
+ else None
156
+ ),
157
+ **dict(group.metadata),
158
+ },
159
+ )
160
+
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
+ def snapshot(self) -> dict[str, Any]:
195
+ return {
196
+ "version": DIAGNOSTICS_VERSION,
197
+ "summary": _json_safe(self.summary),
198
+ "events": list(self.events),
199
+ "dropped_events": self.dropped_events,
200
+ }
201
+
202
+
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
+ def _json_safe(value: Any, *, depth: int = 0) -> Any:
296
+ if depth > 6:
297
+ return str(value)
298
+ if value is None or isinstance(value, str | int | float | bool):
299
+ return value
300
+ if isinstance(value, Mapping):
301
+ return {
302
+ str(key): _json_safe(item, depth=depth + 1)
303
+ for key, item in value.items()
304
+ }
305
+ if isinstance(value, Sequence) and not isinstance(value, str | bytes | bytearray):
306
+ return [_json_safe(item, depth=depth + 1) for item in value]
307
+ if hasattr(value, "value"):
308
+ return value.value
309
+ return str(value)
@@ -0,0 +1,254 @@
1
+ """CI report helpers for protected semantic guardrails."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Iterable, Mapping, Sequence
7
+ from typing import Any
8
+
9
+ from intentumdiff.core.models import (
10
+ GuardrailCheckResult,
11
+ GuardrailSeverity,
12
+ GuardrailViolation,
13
+ NodePosition,
14
+ SemanticDiff,
15
+ )
16
+
17
+
18
+ def build_guardrail_check_result(
19
+ violations: Iterable[GuardrailViolation],
20
+ *,
21
+ checked_files: int,
22
+ strict: bool,
23
+ metadata: Mapping[str, Any] | None = None,
24
+ ) -> GuardrailCheckResult:
25
+ """Build a counted, JSON-safe guardrail check result."""
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
+ )
44
+
45
+
46
+ def guardrail_result_from_diffs(
47
+ diffs: SemanticDiff | Sequence[SemanticDiff],
48
+ *,
49
+ strict: bool,
50
+ checked_files: int | None = None,
51
+ metadata: Mapping[str, Any] | None = None,
52
+ ) -> GuardrailCheckResult:
53
+ """Collect guardrail evidence from one or more semantic diffs."""
54
+
55
+ items = [diffs] if isinstance(diffs, SemanticDiff) else list(diffs)
56
+ violations = [
57
+ violation
58
+ for diff in items
59
+ for violation in diff.guardrail_violations
60
+ ]
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
+ )
67
+
68
+
69
+ def render_guardrail_json(result: GuardrailCheckResult, *, indent: int = 2) -> str:
70
+ """Render a guardrail check result as JSON."""
71
+
72
+ return result.model_dump_json(indent=indent)
73
+
74
+
75
+ def render_guardrail_annotations(result: GuardrailCheckResult) -> str:
76
+ """Render GitHub Actions workflow commands for guardrail violations."""
77
+
78
+ lines = [_annotation_line(violation) for violation in result.violations]
79
+ return "\n".join(lines)
80
+
81
+
82
+ def render_guardrail_sarif(result: GuardrailCheckResult, *, indent: int = 2) -> str:
83
+ """Render guardrail violations as a SARIF 2.1.0 report."""
84
+
85
+ return json.dumps(sarif_from_guardrail_result(result), indent=indent)
86
+
87
+
88
+ def render_guardrail_terminal(result: GuardrailCheckResult) -> str:
89
+ """Render a compact terminal summary for ``intentumdiff guardrails check``."""
90
+
91
+ if not result.violations:
92
+ return (
93
+ f"Guardrail check passed: {result.checked_files} file(s) checked; "
94
+ "no protected semantic changes."
95
+ )
96
+
97
+ lines = [
98
+ (
99
+ "Guardrail check found "
100
+ f"{result.violation_count} protected semantic change(s): "
101
+ f"{result.immutable_count} immutable, "
102
+ f"{result.important_count} important."
103
+ )
104
+ ]
105
+ for violation in result.violations:
106
+ location = _display_location(violation)
107
+ lines.append(
108
+ f"- {violation.severity.value.upper()} {location} "
109
+ f"{violation.rule_id}: {violation.message}"
110
+ )
111
+ return "\n".join(lines)
112
+
113
+
114
+ def sarif_from_guardrail_result(result: GuardrailCheckResult) -> dict[str, Any]:
115
+ """Build the SARIF object used by JSON renderers and tests."""
116
+
117
+ rules_by_id: dict[str, dict[str, Any]] = {}
118
+ for violation in result.violations:
119
+ rules_by_id.setdefault(
120
+ violation.rule_id,
121
+ {
122
+ "id": violation.rule_id,
123
+ "name": violation.rule_id,
124
+ "shortDescription": {
125
+ "text": violation.message or "Protected semantic path changed",
126
+ },
127
+ "properties": {
128
+ "semanticPath": violation.semantic_path,
129
+ "language": violation.language,
130
+ },
131
+ },
132
+ )
133
+
134
+ return {
135
+ "version": "2.1.0",
136
+ "$schema": (
137
+ "https://json.schemastore.org/sarif-2.1.0.json"
138
+ ),
139
+ "runs": [
140
+ {
141
+ "tool": {
142
+ "driver": {
143
+ "name": "IntentumDiff",
144
+ "informationUri": (
145
+ "https://github.com/buchochelliq-labs/intentumdiff"
146
+ ),
147
+ "rules": list(rules_by_id.values()),
148
+ }
149
+ },
150
+ "results": [
151
+ _sarif_result(violation)
152
+ for violation in result.violations
153
+ ],
154
+ }
155
+ ],
156
+ }
157
+
158
+
159
+ def _annotation_line(violation: GuardrailViolation) -> str:
160
+ level = (
161
+ "error"
162
+ if violation.severity == GuardrailSeverity.IMMUTABLE
163
+ else "warning"
164
+ )
165
+ properties = [
166
+ f"file={_escape_annotation_property(violation.file)}",
167
+ f"title={_escape_annotation_property(_annotation_title(violation))}",
168
+ ]
169
+ if violation.position is not None:
170
+ line, column, _, _ = _region(violation.position)
171
+ properties.extend([f"line={line}", f"col={column}"])
172
+
173
+ message = violation.message or "Protected semantic path changed"
174
+ if violation.old_value or violation.new_value:
175
+ message = f"{message}: {violation.old_value!r} -> {violation.new_value!r}"
176
+ return (
177
+ f"::{level} {','.join(properties)}::"
178
+ f"{_escape_annotation_message(message)}"
179
+ )
180
+
181
+
182
+ def _annotation_title(violation: GuardrailViolation) -> str:
183
+ return f"{violation.severity.value} guardrail {violation.rule_id}"
184
+
185
+
186
+ def _escape_annotation_message(value: str) -> str:
187
+ return (
188
+ value.replace("%", "%25")
189
+ .replace("\r", "%0D")
190
+ .replace("\n", "%0A")
191
+ )
192
+
193
+
194
+ def _escape_annotation_property(value: str) -> str:
195
+ return (
196
+ _escape_annotation_message(value)
197
+ .replace(":", "%3A")
198
+ .replace(",", "%2C")
199
+ )
200
+
201
+
202
+ def _sarif_result(violation: GuardrailViolation) -> dict[str, Any]:
203
+ result: dict[str, Any] = {
204
+ "ruleId": violation.rule_id,
205
+ "level": (
206
+ "error"
207
+ if violation.severity == GuardrailSeverity.IMMUTABLE
208
+ else "warning"
209
+ ),
210
+ "message": {
211
+ "text": violation.message or "Protected semantic path changed",
212
+ },
213
+ "locations": [_sarif_location(violation)],
214
+ "properties": {
215
+ "semanticPath": violation.semantic_path,
216
+ "language": violation.language,
217
+ "nodeType": violation.node_type,
218
+ },
219
+ }
220
+ if violation.old_value or violation.new_value:
221
+ result["properties"]["oldValue"] = violation.old_value
222
+ result["properties"]["newValue"] = violation.new_value
223
+ return result
224
+
225
+
226
+ def _sarif_location(violation: GuardrailViolation) -> dict[str, Any]:
227
+ physical: dict[str, Any] = {
228
+ "artifactLocation": {"uri": violation.file},
229
+ }
230
+ if violation.position is not None:
231
+ start_line, start_col, end_line, end_col = _region(violation.position)
232
+ physical["region"] = {
233
+ "startLine": start_line,
234
+ "startColumn": start_col,
235
+ "endLine": end_line,
236
+ "endColumn": end_col,
237
+ }
238
+ return {"physicalLocation": physical}
239
+
240
+
241
+ def _region(position: NodePosition) -> tuple[int, int, int, int]:
242
+ 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),
247
+ )
248
+
249
+
250
+ def _display_location(violation: GuardrailViolation) -> str:
251
+ if violation.position is None:
252
+ return f"{violation.file}::{violation.semantic_path}"
253
+ line, column, _, _ = _region(violation.position)
254
+ return f"{violation.file}:{line}:{column}::{violation.semantic_path}"