intentumdiff-python 0.0.1__py3-none-win_arm64.whl → 0.0.2b2__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 (139) hide show
  1. intentumdiff/__init__.py +2 -0
  2. intentumdiff/__main__.py +12 -0
  3. intentumdiff/_differ_presentation.py +35 -682
  4. intentumdiff/_differ_runtime.py +13 -47
  5. intentumdiff/analysis/compile_commands.py +26 -141
  6. intentumdiff/analysis/cross_file.py +2 -4
  7. intentumdiff/analysis/guardrail_reports.py +7 -5
  8. intentumdiff/analysis/guardrails.py +110 -122
  9. intentumdiff/analysis/invariances.py +4 -1003
  10. intentumdiff/analysis/schema_resolver.py +49 -273
  11. intentumdiff/analysis/text_review.py +4 -3
  12. intentumdiff/analysis/user_schemas.py +55 -237
  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 +174 -67
  17. intentumdiff/cli/_parser.py +11 -1
  18. intentumdiff/cli/_shared.py +96 -112
  19. intentumdiff/content_type.py +13 -30
  20. intentumdiff/core/commit_differ.py +105 -220
  21. intentumdiff/core/diffignore.py +28 -34
  22. intentumdiff/core/index.py +16 -18
  23. intentumdiff/core/indexer.py +148 -168
  24. intentumdiff/core/models.py +53 -14
  25. intentumdiff/differ.py +278 -605
  26. intentumdiff/github_app.py +35 -19
  27. intentumdiff/intentumdiff_rust_core/intentumdiff_rust_core.dll +0 -0
  28. intentumdiff/live_server.py +180 -17
  29. intentumdiff/lsp/client.py +7 -1
  30. intentumdiff/lsp/enricher.py +19 -119
  31. intentumdiff/lsp/exceptions.py +6 -7
  32. intentumdiff/lsp_server/_codelens.py +24 -57
  33. intentumdiff/lsp_server/_diagnostics.py +23 -51
  34. intentumdiff/lsp_server/_handlers.py +66 -8
  35. intentumdiff/lsp_server/server.py +28 -7
  36. intentumdiff/plugins/adapter.py +5 -0
  37. intentumdiff/plugins/builtins.py +7 -14
  38. intentumdiff/plugins/exceptions.py +4 -0
  39. intentumdiff/plugins/hub.py +1 -2
  40. intentumdiff/plugins/loader.py +229 -215
  41. intentumdiff/plugins/registry.py +249 -197
  42. intentumdiff/rust_core.py +744 -784
  43. intentumdiff/serve/_app.py +3 -10
  44. intentumdiff/sources/base.py +24 -0
  45. intentumdiff/sources/file_source.py +15 -2
  46. intentumdiff/sources/git_source.py +120 -58
  47. intentumdiff/sources/live_buffer_source.py +45 -5
  48. intentumdiff/sources/patch_source.py +36 -109
  49. intentumdiff/vcs/_safe_path.py +7 -0
  50. intentumdiff/vcs/base.py +6 -0
  51. intentumdiff/vcs/git_backend.py +1 -1
  52. intentumdiff/vcs/git_cli.py +38 -18
  53. intentumdiff/vcs/hg_backend.py +1 -1
  54. intentumdiff/vcs/perforce_backend.py +7 -1
  55. intentumdiff/vcs/svn_backend.py +1 -1
  56. intentumdiff/wasm/abap_parser.wasm +0 -0
  57. intentumdiff/wasm/adf_parser.wasm +0 -0
  58. intentumdiff/wasm/asciidoc_parser.wasm +0 -0
  59. intentumdiff/wasm/asm_parser.wasm +0 -0
  60. intentumdiff/wasm/assemblyscript_parser.wasm +0 -0
  61. intentumdiff/wasm/astro_parser.wasm +0 -0
  62. intentumdiff/wasm/bash_parser.wasm +0 -0
  63. intentumdiff/wasm/clojure_parser.wasm +0 -0
  64. intentumdiff/wasm/cmake_parser.wasm +0 -0
  65. intentumdiff/wasm/cpp_parser.wasm +0 -0
  66. intentumdiff/wasm/csharp_parser.wasm +0 -0
  67. intentumdiff/wasm/css_parser.wasm +0 -0
  68. intentumdiff/wasm/dart_parser.wasm +0 -0
  69. intentumdiff/wasm/databricks_parser.wasm +0 -0
  70. intentumdiff/wasm/dax_parser.wasm +0 -0
  71. intentumdiff/wasm/delphi_parser.wasm +0 -0
  72. intentumdiff/wasm/dockerfile_parser.wasm +0 -0
  73. intentumdiff/wasm/elixir_parser.wasm +0 -0
  74. intentumdiff/wasm/freebasic_parser.wasm +0 -0
  75. intentumdiff/wasm/generic_parser.wasm +0 -0
  76. intentumdiff/wasm/gitignore_parser.wasm +0 -0
  77. intentumdiff/wasm/go_parser.wasm +0 -0
  78. intentumdiff/wasm/gomod_parser.wasm +0 -0
  79. intentumdiff/wasm/graphql_parser.wasm +0 -0
  80. intentumdiff/wasm/groovy_parser.wasm +0 -0
  81. intentumdiff/wasm/haskell_parser.wasm +0 -0
  82. intentumdiff/wasm/html_parser.wasm +0 -0
  83. intentumdiff/wasm/html_renderer.wasm +0 -0
  84. intentumdiff/wasm/ini_parser.wasm +0 -0
  85. intentumdiff/wasm/java_parser.wasm +0 -0
  86. intentumdiff/wasm/js_ts_parser.wasm +0 -0
  87. intentumdiff/wasm/json_parser.wasm +0 -0
  88. intentumdiff/wasm/kotlin_parser.wasm +0 -0
  89. intentumdiff/wasm/latex_parser.wasm +0 -0
  90. intentumdiff/wasm/llm_renderer.wasm +0 -0
  91. intentumdiff/wasm/lua_parser.wasm +0 -0
  92. intentumdiff/wasm/make_parser.wasm +0 -0
  93. intentumdiff/wasm/markdown_parser.wasm +0 -0
  94. intentumdiff/wasm/mdx_parser.wasm +0 -0
  95. intentumdiff/wasm/ocaml_parser.wasm +0 -0
  96. intentumdiff/wasm/odin_parser.wasm +0 -0
  97. intentumdiff/wasm/parser_manifest.json +81 -2
  98. intentumdiff/wasm/patch_renderer.wasm +0 -0
  99. intentumdiff/wasm/perl_parser.wasm +0 -0
  100. intentumdiff/wasm/php_parser.wasm +0 -0
  101. intentumdiff/wasm/plsql_parser.wasm +0 -0
  102. intentumdiff/wasm/po_parser.wasm +0 -0
  103. intentumdiff/wasm/postscript_parser.wasm +0 -0
  104. intentumdiff/wasm/powershell_parser.wasm +0 -0
  105. intentumdiff/wasm/proto_parser.wasm +0 -0
  106. intentumdiff/wasm/puppet_parser.wasm +0 -0
  107. intentumdiff/wasm/python_parser.wasm +0 -0
  108. intentumdiff/wasm/qsharp_parser.wasm +0 -0
  109. intentumdiff/wasm/r_parser.wasm +0 -0
  110. intentumdiff/wasm/reasonml_parser.wasm +0 -0
  111. intentumdiff/wasm/ruby_parser.wasm +0 -0
  112. intentumdiff/wasm/rust_parser.wasm +0 -0
  113. intentumdiff/wasm/sas_parser.wasm +0 -0
  114. intentumdiff/wasm/scala_parser.wasm +0 -0
  115. intentumdiff/wasm/scss_parser.wasm +0 -0
  116. intentumdiff/wasm/sql_parser.wasm +0 -0
  117. intentumdiff/wasm/squirrel_parser.wasm +0 -0
  118. intentumdiff/wasm/svelte_parser.wasm +0 -0
  119. intentumdiff/wasm/swift_parser.wasm +0 -0
  120. intentumdiff/wasm/terminal_renderer.wasm +0 -0
  121. intentumdiff/wasm/terraform_parser.wasm +0 -0
  122. intentumdiff/wasm/toml_parser.wasm +0 -0
  123. intentumdiff/wasm/tsql_parser.wasm +0 -0
  124. intentumdiff/wasm/vbnet_parser.wasm +0 -0
  125. intentumdiff/wasm/vue_parser.wasm +0 -0
  126. intentumdiff/wasm/wasm_provenance.json +884 -0
  127. intentumdiff/wasm/wat_parser.wasm +0 -0
  128. intentumdiff/wasm/xml_parser.wasm +0 -0
  129. intentumdiff/wasm/yaml_parser.wasm +0 -0
  130. intentumdiff/wasm/zig_parser.wasm +0 -0
  131. intentumdiff_python-0.0.2b2.dist-info/METADATA +156 -0
  132. intentumdiff_python-0.0.2b2.dist-info/RECORD +171 -0
  133. {intentumdiff_python-0.0.1.dist-info → intentumdiff_python-0.0.2b2.dist-info}/WHEEL +1 -1
  134. {intentumdiff_python-0.0.1.dist-info → intentumdiff_python-0.0.2b2.dist-info}/sboms/intentumdiff-rust-core.cyclonedx.json +905 -379
  135. intentumdiff/core/cst_serializer.py +0 -101
  136. intentumdiff_python-0.0.1.dist-info/METADATA +0 -112
  137. intentumdiff_python-0.0.1.dist-info/RECORD +0 -165
  138. {intentumdiff_python-0.0.1.dist-info → intentumdiff_python-0.0.2b2.dist-info}/entry_points.txt +0 -0
  139. {intentumdiff_python-0.0.1.dist-info → intentumdiff_python-0.0.2b2.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:
@@ -126,12 +92,12 @@ def _attach_content_type_metadata(
126
92
  """Enrich a diff's metadata with the detected content type (mime + category).
127
93
 
128
94
  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.
95
+ surfaces can show what kind of file was diffed. Malformed UTF-8 source
96
+ and required Rust detector failures propagate; no fabricated bytes/fallback.
131
97
  """
132
98
  from intentumdiff.content_type import detect_content_type
133
99
 
134
- head = (new_content or old_content)[:8192].encode("utf-8", errors="replace")
100
+ head = (new_content or old_content)[:8192].encode("utf-8", errors="strict")
135
101
  metadata = dict(diff.metadata or {})
136
102
  metadata["content_type"] = detect_content_type(head)
137
103
  return diff.model_copy(update={"metadata": metadata})
@@ -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,8 +45,6 @@ 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
49
  changes: list[CrossFileChange] = []
52
50
  for item in result:
@@ -142,7 +142,7 @@ def sarif_from_guardrail_result(result: GuardrailCheckResult) -> dict[str, Any]:
142
142
  "driver": {
143
143
  "name": "IntentumDiff",
144
144
  "informationUri": (
145
- "https://github.com/buchochelliq-labs/intentumdiff"
145
+ "https://buchochelliq-labs.github.io/intentumdiff-docs/"
146
146
  ),
147
147
  "rules": list(rules_by_id.values()),
148
148
  }
@@ -239,11 +239,13 @@ def _sarif_location(violation: GuardrailViolation) -> dict[str, Any]:
239
239
 
240
240
 
241
241
  def _region(position: NodePosition) -> tuple[int, int, int, int]:
242
+ # Rust/C ABI positions are zero-based; SARIF and GitHub annotations are
243
+ # one-based. Clamping collapses line/column 0 and 1 into the same value.
242
244
  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),
245
+ position.start_line + 1,
246
+ position.start_col + 1,
247
+ position.end_line + 1,
248
+ position.end_col + 1,
247
249
  )
248
250
 
249
251
 
@@ -6,9 +6,7 @@ import json
6
6
  from collections.abc import Iterable
7
7
  from dataclasses import dataclass
8
8
  from pathlib import Path
9
- from typing import Any
10
9
 
11
- import yaml
12
10
 
13
11
  from intentumdiff.analysis.diagnostics import DiagnosticsRecorder
14
12
  from intentumdiff.analysis.keyed_profiles import KEYED_DATA_LANGUAGES
@@ -50,15 +48,18 @@ def guardrails_may_apply(
50
48
 
51
49
  if not config.guardrails_enabled:
52
50
  return False
53
- if _is_policy_file(filename) or (new_filename is not None and _is_policy_file(new_filename)):
54
- return True
55
- policy_path = _find_policy_path(filename, config.guardrail_policy_path)
56
- if policy_path is None:
57
- return False
58
- try:
59
- return bool(load_guardrail_policy(filename, explicit_path=policy_path).rules)
60
- except ValueError:
61
- return True
51
+ # Both sides of a move can have a policy. Checking only the destination
52
+ # silently releases protection on moves out of a guarded directory (#262).
53
+ # An explicit policy is mandatory even before a certified Rust batch return
54
+ # (#261); all YAML semantics and rule evaluation remain Rust-owned.
55
+ policies = _load_relevant_guardrail_policies(
56
+ filename, new_filename, config.guardrail_policy_path
57
+ )
58
+ return (
59
+ _is_policy_file(filename)
60
+ or _is_policy_file(new_filename)
61
+ or any(policy.rules for policy in policies)
62
+ )
62
63
 
63
64
 
64
65
  def load_guardrail_policy(
@@ -68,24 +69,59 @@ def load_guardrail_policy(
68
69
  ) -> GuardrailPolicy:
69
70
  policy_path = _find_policy_path(filename, explicit_path)
70
71
  if policy_path is None:
72
+ # An EXPLICIT --policy is the caller asserting that file exists. Returning an empty
73
+ # policy here is a fail-OPEN: the check then reports "Guardrail check passed" and
74
+ # exits 0 with nothing on stderr, so a typo in the path is indistinguishable from a
75
+ # clean run. For a gate whose documented purpose is stopping API keys changing
76
+ # unreviewed, that is the worst possible default.
77
+ #
78
+ # Auto-discovery finding nothing is different and stays permissive: the user never
79
+ # claimed a policy existed.
80
+ if explicit_path is not None:
81
+ raise FileNotFoundError(
82
+ f"Guardrail policy not found: {explicit_path}. "
83
+ "The check would otherwise pass with no rules loaded, which looks identical "
84
+ "to a clean run."
85
+ )
71
86
  return GuardrailPolicy(path=None, rules=())
72
87
 
73
- raw = yaml.safe_load(policy_path.read_text(encoding="utf-8")) or {}
74
- if not isinstance(raw, dict):
75
- raise ValueError(f"{policy_path} must contain a YAML mapping")
88
+ from intentumdiff.rust_core import _c_abi_call
76
89
 
77
- guardrails = raw.get("guardrails", raw)
78
- if not isinstance(guardrails, dict):
79
- raise ValueError(f"{policy_path} guardrails section must be a mapping")
90
+ try:
91
+ rules = _c_abi_call("parse_guardrail_policy", policy_path.read_text(encoding="utf-8"))
92
+ except ValueError as exc:
93
+ raise ValueError(f"{policy_path}: {exc}") from exc
94
+ return GuardrailPolicy(path=policy_path, rules=tuple(
95
+ ProtectedRule(rule_id=rule["rule_id"], severity=GuardrailSeverity(rule["severity"]),
96
+ language=rule["language"], path=rule["path"], message=rule["message"],
97
+ files=tuple(rule["files"])) for rule in rules))
80
98
 
81
- protected = guardrails.get("protected", [])
82
- if protected is None:
83
- protected = []
84
- if not isinstance(protected, list):
85
- raise ValueError(f"{policy_path} guardrails.protected must be a list")
86
99
 
87
- rules = tuple(_parse_rule(item, index, policy_path) for index, item in enumerate(protected))
88
- return GuardrailPolicy(path=policy_path, rules=rules)
100
+ def _load_relevant_guardrail_policies(
101
+ old_filename: str,
102
+ new_filename: str | None,
103
+ explicit_path: Path | None,
104
+ ) -> tuple[GuardrailPolicy, ...]:
105
+ """Discover distinct host policy files for both sides; Rust owns their meaning."""
106
+ if explicit_path is not None:
107
+ # An explicit policy overrides auto-discovery and is required to exist.
108
+ # load_guardrail_policy raises instead of manufacturing no rules (#261).
109
+ return (load_guardrail_policy(new_filename or old_filename,
110
+ explicit_path=explicit_path),)
111
+
112
+ found: list[GuardrailPolicy] = []
113
+ seen_paths: set[Path] = set()
114
+ for filename in (old_filename, new_filename):
115
+ if not filename:
116
+ continue
117
+ policy_path = _find_policy_path(filename, None)
118
+ if policy_path is None or policy_path in seen_paths:
119
+ continue
120
+ seen_paths.add(policy_path)
121
+ # Malformed, dangling or unreadable policies must fail closed even
122
+ # when the other side of the move contains a valid policy.
123
+ found.append(load_guardrail_policy(filename, explicit_path=policy_path))
124
+ return tuple(found)
89
125
 
90
126
 
91
127
  def apply_guardrails_to_diff(
@@ -97,36 +133,39 @@ def apply_guardrails_to_diff(
97
133
  new_source: str,
98
134
  config: DiffConfig,
99
135
  diagnostics: DiagnosticsRecorder | None = None,
136
+ policy_filename: str | None = None,
137
+ policy_old_filename: str | None = None,
100
138
  ) -> SemanticDiff:
101
139
  if not config.guardrails_enabled:
102
140
  return diff
103
141
 
104
- violations: list[GuardrailViolation] = []
105
- if (old_source != new_source) and (
106
- _is_policy_file(diff.old_filename) or _is_policy_file(diff.new_filename)
107
- ):
108
- violations.append(
109
- GuardrailViolation(
110
- rule_id="intentumdiff.policy_file",
111
- severity=GuardrailSeverity.IMMUTABLE,
112
- file=diff.new_filename or diff.old_filename,
113
- language=diff.language,
114
- semantic_path=GUARDRAIL_POLICY_FILENAME,
115
- old_value="project policy",
116
- new_value="project policy",
117
- message="Project guardrail policy changed",
118
- )
119
- )
142
+ from dataclasses import asdict
143
+ from intentumdiff.rust_core import _c_abi_call, _require_complete_batch_diff_dto
120
144
 
121
- policy = load_guardrail_policy(
122
- diff.new_filename or diff.old_filename,
123
- explicit_path=config.guardrail_policy_path,
145
+ # FileSource transports the physical identities for both sides, preserving
146
+ # user-facing aliases. For cross-directory moves include both applicable
147
+ # policy files; only Rust interprets and matches their rules (#262).
148
+ policies = _load_relevant_guardrail_policies(
149
+ policy_old_filename or diff.old_filename,
150
+ policy_filename or diff.new_filename,
151
+ config.guardrail_policy_path,
124
152
  )
125
- if policy.rules and old_tree is not None and new_tree is not None:
126
- violations.extend(_evaluate_policy_rules(diff, old_tree, new_tree, policy.rules))
127
-
128
- if not violations:
129
- return diff
153
+ request = {
154
+ "diff": diff.model_dump(mode="json"),
155
+ "old_tree": old_tree.model_dump(mode="json") if old_tree else None,
156
+ "new_tree": new_tree.model_dump(mode="json") if new_tree else None,
157
+ "old_source": old_source, "new_source": new_source,
158
+ "rules": [asdict(rule) for policy in policies for rule in policy.rules],
159
+ }
160
+ # Pure host-I/O provenance: Rust selects filename-scoped rules and
161
+ # immutable policy-file warnings; public labels remain untouched (#260).
162
+ if policy_filename is not None:
163
+ request["guardrail_new_filename"] = policy_filename
164
+ if policy_old_filename is not None:
165
+ request["guardrail_old_filename"] = policy_old_filename
166
+ response = _c_abi_call("apply_guardrail_policy", json.dumps(request))
167
+ result = SemanticDiff.model_validate(_require_complete_batch_diff_dto(response))
168
+ violations = result.guardrail_violations[len(diff.guardrail_violations):]
130
169
 
131
170
  if diagnostics is not None and diagnostics.enabled:
132
171
  for violation in violations:
@@ -156,64 +195,7 @@ def apply_guardrails_to_diff(
156
195
  },
157
196
  )
158
197
 
159
- metadata = dict(diff.metadata)
160
- metadata["guardrails"] = {
161
- "violation_count": len(violations),
162
- "immutable_count": sum(
163
- violation.severity == GuardrailSeverity.IMMUTABLE for violation in violations
164
- ),
165
- }
166
- return diff.model_copy(
167
- update={
168
- "guardrail_violations": [*diff.guardrail_violations, *violations],
169
- "metadata": metadata,
170
- }
171
- )
172
-
173
-
174
- def _parse_rule(raw: Any, index: int, policy_path: Path) -> ProtectedRule:
175
- if not isinstance(raw, dict):
176
- raise ValueError(f"{policy_path} guardrails.protected[{index}] must be a mapping")
177
-
178
- language = str(raw.get("language", "")).strip().lower()
179
- if language not in GUARDRAIL_CONFIG_LANGUAGES:
180
- raise ValueError(
181
- f"{policy_path} guardrails.protected[{index}] targets unsupported "
182
- f"language {language!r}; protected guardrails currently support "
183
- f"{sorted(GUARDRAIL_CONFIG_LANGUAGES)}"
184
- )
185
-
186
- path = _normalise_path(raw.get("path", ""))
187
- if not path:
188
- raise ValueError(f"{policy_path} guardrails.protected[{index}] requires path")
189
-
190
- severity_text = str(raw.get("severity", GuardrailSeverity.IMPORTANT.value)).lower()
191
- try:
192
- severity = GuardrailSeverity(severity_text)
193
- except ValueError as exc:
194
- raise ValueError(
195
- f"{policy_path} guardrails.protected[{index}] has unsupported "
196
- f"severity {severity_text!r}"
197
- ) from exc
198
-
199
- files = raw.get("files", ())
200
- if isinstance(files, str):
201
- file_patterns = (files,)
202
- elif isinstance(files, list):
203
- file_patterns = tuple(str(item) for item in files)
204
- elif files in (None, ()):
205
- file_patterns = ()
206
- else:
207
- raise ValueError(f"{policy_path} guardrails.protected[{index}].files is invalid")
208
-
209
- return ProtectedRule(
210
- rule_id=str(raw.get("id") or f"guardrail.{index + 1}"),
211
- severity=severity,
212
- language=language,
213
- path=path,
214
- message=str(raw.get("message") or f"Protected path {path} changed"),
215
- files=file_patterns,
216
- )
198
+ return result
217
199
 
218
200
 
219
201
  def _evaluate_policy_rules(
@@ -227,7 +209,7 @@ def _evaluate_policy_rules(
227
209
  semantic-path derivation. Python marshals the parsed policy + the diff's
228
210
  changed-node ids in and rebuilds GuardrailViolation objects out; the Python
229
211
  matching mirror (rule loop, ``_semantic_paths``, ``_node_value_summary``,
230
- ``_file_matches``) was deleted. Returns ``[]`` when the core is unavailable.
212
+ ``_file_matches``) was deleted. Engine failures raise; only a successful empty result means no violations.
231
213
  """
232
214
  from intentumdiff.rust_core import try_rust_evaluate_guardrail_rules
233
215
 
@@ -278,16 +260,6 @@ def _evaluate_policy_rules(
278
260
  ]
279
261
 
280
262
 
281
- def _normalise_path(value: Any) -> str:
282
- text = str(value).strip().strip(".")
283
- return ".".join(_clean_path_part(part) for part in text.split(".") if part)
284
-
285
-
286
- def _clean_path_part(value: str) -> str:
287
- text = str(value).strip().strip('"').strip("'")
288
- return text.lower()
289
-
290
-
291
263
  def _is_policy_file(filename: str | None) -> bool:
292
264
  return Path(filename or "").name.lower() == GUARDRAIL_POLICY_FILENAME
293
265
 
@@ -299,20 +271,36 @@ def _find_policy_path(filename: str, explicit_path: Path | None) -> Path | None:
299
271
  starts: list[Path] = []
300
272
  raw = Path(filename)
301
273
  if filename and not filename.startswith("<"):
302
- starts.append(raw if raw.is_dir() else raw.parent)
303
- starts.append(Path.cwd())
274
+ # The argument identifies a source *file*, even if its current checkout
275
+ # entry is a symlink to a directory. Do not follow that final component
276
+ # into unrelated external policy directories for a historical Git diff.
277
+ # For relative paths, the parent resolves against cwd already. An
278
+ # absolute path must never fall back to an unrelated process cwd.
279
+ starts.append(raw.parent)
280
+ else:
281
+ # Synthetic/in-memory sources have no physical policy-search origin.
282
+ starts.append(Path.cwd())
304
283
 
305
284
  seen: set[Path] = set()
306
285
  for start in starts:
307
286
  try:
308
287
  current = start.resolve()
309
- except OSError:
310
- current = Path.cwd()
288
+ except OSError as exc:
289
+ # A failed physical-path resolution is not permission to import
290
+ # a policy from another repository's process working directory.
291
+ # Report the host I/O failure instead of manufacturing a clean (or
292
+ # foreign-policy) guardrail result.
293
+ raise RuntimeError(
294
+ f"Unable to resolve guardrail policy search path {start}: {exc}"
295
+ ) from exc
311
296
  for directory in (current, *current.parents):
312
297
  if directory in seen:
313
298
  continue
314
299
  seen.add(directory)
315
300
  candidate = directory / GUARDRAIL_POLICY_FILENAME
316
- if candidate.exists():
301
+ # A dangling symlink is an explicitly present but unusable policy.
302
+ # Treating it as absent would silently disable protected-change checks.
303
+ # The subsequent strict read must report the missing target instead.
304
+ if candidate.exists() or candidate.is_symlink():
317
305
  return candidate
318
306
  return None