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
@@ -309,17 +309,10 @@ def create_app(
309
309
  return _request_body_too_large_response()
310
310
  chunks.append(chunk)
311
311
  body = b"".join(chunks)
312
- sent = False
313
-
314
- async def receive(): # type: ignore[no-untyped-def]
315
- nonlocal sent
316
- if sent:
317
- return {"type": "http.request", "body": b"", "more_body": False}
318
- sent = True
319
- return {"type": "http.request", "body": body, "more_body": False}
320
-
312
+ # BaseHTTPMiddleware replays the cached body through wrapped_receive.
313
+ # Preserve the original receive callable so its next event is the real
314
+ # upstream disconnect, rather than a second replayed request.
321
315
  request._body = body # type: ignore[attr-defined]
322
- request._receive = receive # type: ignore[attr-defined]
323
316
  return await call_next(request)
324
317
 
325
318
  if cors_origins is not None:
@@ -26,3 +26,27 @@ class Source(ABC):
26
26
  ``language_hint`` — e.g. "python", "sql". Pass None to auto-detect.
27
27
  """
28
28
  ...
29
+
30
+ def guardrail_policy_paths(self) -> tuple[str | None, str | None]:
31
+ """Return host filesystem paths for old/new guardrail policy discovery.
32
+
33
+ Source display labels are NOT physical policy identities. The default
34
+ has no filesystem context; adapters for real files/repos override it.
35
+ Rust alone interprets policy rules and evaluates semantic violations.
36
+ """
37
+ return None, None
38
+
39
+ def display_names(self) -> tuple[str, str] | None:
40
+ """
41
+ Distinct ``(old, new)`` names, when the two sides are named differently.
42
+
43
+ ``get_content`` returns ONE filename because that is what language detection
44
+ needs, and for most sources it is also the right thing to display: a git diff
45
+ compares one path at two revisions, so both sides share a name.
46
+
47
+ ``FileSource`` is the exception — it compares two separately named files — and
48
+ collapsing both sides onto the new name made the CLI report that it had diffed
49
+ a file with itself. Sources that know two names override this; ``None`` means
50
+ "one name applies to both", which stays the default.
51
+ """
52
+ return None
@@ -43,6 +43,19 @@ class FileSource(Source):
43
43
  self._filename = filename or self._new_path.name
44
44
 
45
45
  def get_content(self) -> tuple[str, str, str, str | None]:
46
- old_content = self._old_path.read_text(encoding="utf-8", errors="replace")
47
- new_content = self._new_path.read_text(encoding="utf-8", errors="replace")
46
+ old_content = self._old_path.read_text(encoding="utf-8", errors="strict")
47
+ new_content = self._new_path.read_text(encoding="utf-8", errors="strict")
48
48
  return old_content, new_content, self._filename, self._language_hint
49
+
50
+ def guardrail_policy_paths(self) -> tuple[str, str]:
51
+ """Preserve the two real file locations independently of display aliases."""
52
+ return str(self._old_path), str(self._new_path)
53
+
54
+ def display_names(self) -> tuple[str, str] | None:
55
+ # This source is the one that genuinely has two names. An explicit ``filename``
56
+ # overrides both, and identical basenames need no distinction.
57
+ if self._filename != self._new_path.name:
58
+ return None
59
+ if self._old_path.name == self._new_path.name:
60
+ return None
61
+ return self._old_path.name, self._new_path.name
@@ -19,8 +19,12 @@ from pathlib import Path
19
19
 
20
20
  from intentumdiff import content_type as _content_type
21
21
  from intentumdiff.sources.base import Source
22
- from intentumdiff.vcs._safe_path import safe_relative_path, safe_working_tree_path
23
- from intentumdiff.vcs.git_cli import resolve_repo_root, run_git_bytes
22
+ from intentumdiff.vcs._safe_path import safe_policy_path, safe_relative_path, safe_working_tree_path
23
+ from intentumdiff.vcs.git_cli import (
24
+ parse_name_status_z as _parse_name_status_z,
25
+ resolve_repo_root,
26
+ run_git_bytes,
27
+ )
24
28
 
25
29
 
26
30
  def _decode_text_or_none(data: bytes) -> str | None:
@@ -32,7 +36,7 @@ def _decode_text_or_none(data: bytes) -> str | None:
32
36
  """
33
37
  if not _content_type.is_text_bytes(data):
34
38
  return None
35
- return data.decode("utf-8", errors="replace")
39
+ return data.decode("utf-8", errors="strict")
36
40
 
37
41
 
38
42
  def _safe_file_path(file_path: str) -> str:
@@ -62,48 +66,45 @@ def _is_python_path(path: str) -> bool:
62
66
 
63
67
 
64
68
  def _decode_git_path(path: bytes) -> str:
65
- return path.decode("utf-8", errors="replace")
69
+ # A Git pathname need not be UTF-8 on every filesystem. Without a
70
+ # lossless byte transport to Rust, reject rather than invent a new name.
71
+ try:
72
+ return path.decode("utf-8", errors="strict")
73
+ except UnicodeDecodeError as exc:
74
+ raise UnicodeError("Invalid UTF-8 in Git pathname") from exc
75
+
76
+
77
+ def _decode_nul_paths(data: bytes, *, source: str) -> list[str]:
78
+ """Require a complete, nonempty Git -z path inventory (#239)."""
79
+ if not data:
80
+ return []
81
+ if not data.endswith(b"\0"):
82
+ raise RuntimeError(f"Incomplete {source} output: missing NUL terminator")
83
+ raw_paths = data[:-1].split(b"\0")
84
+ if any(not path for path in raw_paths):
85
+ raise RuntimeError(f"Empty path in {source} output")
86
+ return [_decode_git_path(path) for path in raw_paths]
66
87
 
67
88
 
68
89
  def _untracked_paths(repo_path: str) -> list[str]:
69
90
  data = run_git_bytes(repo_path, ["ls-files", "--others", "--exclude-standard", "-z"])
70
- return sorted(_decode_git_path(token) for token in data.split(b"\0") if token)
91
+ return sorted(_decode_nul_paths(data, source="git ls-files -z"))
71
92
 
72
93
 
73
94
  def _read_working_tree_text(path: Path) -> str | None:
74
95
  try:
75
96
  data = path.read_bytes()
76
- except OSError:
77
- return None
97
+ except OSError as exc:
98
+ # A failed read of an enumerated untracked file is not evidence that
99
+ # the file is binary; skipping it would certify an incomplete diff (#242).
100
+ raise RuntimeError(
101
+ f"Failed to read untracked working-tree source {path}: {exc}"
102
+ ) from exc
78
103
  # Content-based routing: binary/image assets are skipped (reviewed via the
79
104
  # perceptual asset diff), never decoded and sent to the text engine.
80
105
  return _decode_text_or_none(data)
81
106
 
82
107
 
83
- def _parse_name_status_z(data: bytes) -> list[tuple[str, str, str]]:
84
- tokens = [token for token in data.split(b"\0") if token]
85
- entries: list[tuple[str, str, str]] = []
86
- idx = 0
87
- while idx < len(tokens):
88
- status = tokens[idx].decode("ascii", errors="replace")
89
- idx += 1
90
- code = status[:1]
91
- if code in {"R", "C"}:
92
- if idx + 1 >= len(tokens):
93
- break
94
- old_path = _decode_git_path(tokens[idx])
95
- new_path = _decode_git_path(tokens[idx + 1])
96
- idx += 2
97
- else:
98
- if idx >= len(tokens):
99
- break
100
- old_path = _decode_git_path(tokens[idx])
101
- new_path = old_path
102
- idx += 1
103
- entries.append((code, old_path, new_path))
104
- return entries
105
-
106
-
107
108
  def _read_commit_paths_batch(
108
109
  repo_path: str,
109
110
  rev: str,
@@ -122,26 +123,32 @@ def _read_commit_paths_batch(
122
123
  for path in unique_paths:
123
124
  header_end = output.find(b"\n", pos)
124
125
  if header_end < 0:
125
- raise ValueError("malformed git cat-file batch output")
126
+ raise RuntimeError("malformed git cat-file batch output")
126
127
  header = output[pos:header_end]
127
128
  pos = header_end + 1
128
129
  if header.endswith(b" missing"):
129
- result[path] = ""
130
- continue
130
+ # Every requested non-addition path must exist in the base tree.
131
+ # An empty fallback would manufacture semantic change evidence (#241).
132
+ raise RuntimeError(f"Missing tracked Git baseline {rev}:{path}")
131
133
  parts = header.split()
132
- if len(parts) < 3:
133
- raise ValueError("malformed git cat-file batch header")
134
+ if len(parts) != 3 or parts[1] != b"blob":
135
+ raise RuntimeError("malformed git cat-file batch blob header")
134
136
  try:
135
137
  size = int(parts[2])
136
138
  except ValueError as exc:
137
- raise ValueError("malformed git cat-file batch size") from exc
139
+ raise RuntimeError("malformed git cat-file batch size") from exc
140
+ if size < 0 or pos + size >= len(output) or output[pos + size] != 0x0A:
141
+ raise RuntimeError("incomplete git cat-file batch blob payload")
138
142
  content = output[pos : pos + size]
139
- if len(content) != size:
140
- raise ValueError("truncated git cat-file batch content")
141
- pos += size
142
- if pos < len(output) and output[pos : pos + 1] == b"\n":
143
- pos += 1
144
- result[path] = content.decode("utf-8", errors="replace")
143
+ pos += size + 1 # consume mandatory delimiter
144
+ try:
145
+ result[path] = content.decode("utf-8", errors="strict")
146
+ except UnicodeDecodeError as exc:
147
+ raise UnicodeError(
148
+ f"Invalid UTF-8 in tracked Git baseline {rev}:{path}"
149
+ ) from exc
150
+ if pos != len(output):
151
+ raise RuntimeError("Unexpected extra git cat-file batch output")
145
152
  return result
146
153
 
147
154
 
@@ -163,11 +170,9 @@ def collect_working_tree_python_sources_fast(
163
170
  # sha) is equivalent here and avoids an extra round-trip.
164
171
  old_rev = old_ref
165
172
  diff_output = run_git_bytes(working_dir, ["diff", "--name-status", "-z", old_rev])
166
- entries = [
167
- entry
168
- for entry in _parse_name_status_z(diff_output)
169
- if entry[0] in _TEXT_CHANGE_TYPES
170
- ]
173
+ entries = _parse_name_status_z(diff_output)
174
+ if any(code not in _TEXT_CHANGE_TYPES for code, _, _ in entries):
175
+ return ([], "Unsupported Git change status requires Rust review")
171
176
  untracked_paths = _untracked_paths(working_dir)
172
177
  if not entries and not untracked_paths:
173
178
  return [], None
@@ -188,11 +193,9 @@ def collect_working_tree_python_sources_fast(
188
193
  working_dir,
189
194
  ["diff", "--cached", "--name-only", "-z", old_rev],
190
195
  )
191
- staged_paths = {
192
- _decode_git_path(token)
193
- for token in staged_output.split(b"\0")
194
- if token
195
- }
196
+ staged_paths = set(
197
+ _decode_nul_paths(staged_output, source="git diff --cached --name-only -z")
198
+ )
196
199
  old_paths = [old_path for code, old_path, _new_path in entries if code != "A"]
197
200
  old_contents = _read_commit_paths_batch(working_dir, old_rev, old_paths)
198
201
  sources: list[_ChangedSource] = []
@@ -200,7 +203,7 @@ def collect_working_tree_python_sources_fast(
200
203
  for code, old_path, new_path in entries:
201
204
  _safe_file_path(old_path)
202
205
  _safe_file_path(new_path)
203
- old_content = "" if code == "A" else old_contents.get(old_path, "")
206
+ old_content = "" if code == "A" else old_contents[old_path]
204
207
  if code == "D":
205
208
  new_content = ""
206
209
  else:
@@ -208,10 +211,7 @@ def collect_working_tree_python_sources_fast(
208
211
  if not disk_path.exists():
209
212
  new_content = ""
210
213
  else:
211
- new_content = disk_path.read_text(
212
- encoding="utf-8",
213
- errors="replace",
214
- )
214
+ new_content = disk_path.read_text(encoding="utf-8")
215
215
  staging_status = (
216
216
  "staged"
217
217
  if old_path in staged_paths or new_path in staged_paths
@@ -226,6 +226,10 @@ def collect_working_tree_python_sources_fast(
226
226
  continue
227
227
  sources.append(("", new_content, untracked_path, untracked_path, "untracked"))
228
228
  return sources, None
229
+ except UnicodeError:
230
+ # The optimizer must not turn a bad source encoding into an altered,
231
+ # successful semantic review or silently reroute it as a normal decline.
232
+ raise
229
233
  except (OSError, subprocess.SubprocessError, ValueError):
230
234
  return None
231
235
 
@@ -308,6 +312,17 @@ class GitSource(Source):
308
312
  )
309
313
  return old_content, new_content, self._file_path, self._language_hint
310
314
 
315
+ def guardrail_policy_paths(self) -> tuple[str, str]:
316
+ """Use repository policy context without inspecting a historical blob's live target.
317
+
318
+ Commit-to-commit Git data comes from object storage. A checkout may
319
+ meanwhile replace the tracked file with an external symlink; following
320
+ that unrelated final component must not invalidate historical review.
321
+ Resolve and validate only its parent (where policy discovery begins).
322
+ """
323
+ path = safe_policy_path(self._repo_path, self._file_path)
324
+ return path, path
325
+
311
326
  @classmethod
312
327
  def working_tree(
313
328
  cls,
@@ -331,6 +346,48 @@ class GitSource(Source):
331
346
  )
332
347
 
333
348
 
349
+ class StagedSource(GitSource):
350
+ """Select one file from Rust's index comparison, preserving rename paths."""
351
+
352
+ def __init__(self, repo_path: str | os.PathLike[str], file_path: str,
353
+ ref: str = "HEAD") -> None:
354
+ super().__init__(repo_path, file_path, old_ref=ref, new_ref=_REF_STAGED)
355
+ self._old_path = self._file_path
356
+ self._new_path = self._file_path
357
+
358
+ def get_content(self) -> tuple[str, str, str, str | None]:
359
+ from intentumdiff import rust_core
360
+
361
+ sources = list(iter_changed_sources(self._repo_path, self._old_ref, _REF_STAGED))
362
+ # Prefer the destination when a path is both a rename source and target.
363
+ selected = next((row for row in sources if row[3] == self._file_path), None)
364
+ if selected is None:
365
+ selected = next((row for row in sources if row[2] == self._file_path), None)
366
+ if selected is not None:
367
+ old, new, self._old_path, self._new_path, _status = selected
368
+ return old, new, self._new_path, self._language_hint
369
+ # The text inventory also omits binary entries. Read the actual index
370
+ # bytes before treating an absent row as an unchanged text source.
371
+ self._old_path = self._new_path = self._file_path
372
+ index_bytes = run_git_bytes(
373
+ self._repo_path, ["cat-file", "blob", f":{self._file_path}"]
374
+ )
375
+ new = _decode_text_or_none(index_bytes)
376
+ if new is None:
377
+ raise ValueError(f"Staged source {self._file_path!r} is not text")
378
+ old, _ = rust_core.git_source_content(
379
+ self._repo_path, self._file_path, self._old_ref, self._old_ref
380
+ )
381
+ return old, new, self._file_path, self._language_hint
382
+
383
+ def display_names(self) -> tuple[str, str]:
384
+ return self._old_path, self._new_path
385
+
386
+ def guardrail_policy_paths(self) -> tuple[str, str]:
387
+ return (safe_policy_path(self._repo_path, self._old_path),
388
+ safe_policy_path(self._repo_path, self._new_path))
389
+
390
+
334
391
  class WorkingTreeSource(Source):
335
392
  """
336
393
  Compare the committed version of a file against the current working tree.
@@ -373,3 +430,8 @@ class WorkingTreeSource(Source):
373
430
  self._repo_path, self._file_path, self._ref
374
431
  )
375
432
  return old_content, new_content, self._file_path, self._language_hint
433
+
434
+ def guardrail_policy_paths(self) -> tuple[str, str]:
435
+ """Locate working-tree guardrails in the actual repository root."""
436
+ path = str(safe_working_tree_path(self._repo_path, self._file_path))
437
+ return path, path
@@ -18,7 +18,7 @@ from pathlib import Path, PurePosixPath
18
18
  from typing import TYPE_CHECKING
19
19
 
20
20
  from intentumdiff.sources.base import Source
21
- from intentumdiff.vcs._safe_path import safe_relative_path
21
+ from intentumdiff.vcs._safe_path import safe_relative_path, safe_working_tree_path
22
22
  from intentumdiff.vcs.git_cli import resolve_repo_root, run_git_bytes
23
23
 
24
24
  if TYPE_CHECKING:
@@ -62,6 +62,7 @@ class LiveBufferSource(Source):
62
62
  ref: str = "HEAD",
63
63
  language_hint: str | None = None,
64
64
  edit_deltas: "list[EditDelta] | None" = None,
65
+ cache_snapshot: bool = False,
65
66
  ) -> None:
66
67
  # Validate the file path before storing it.
67
68
  safe = PurePosixPath(file_path)
@@ -77,6 +78,8 @@ class LiveBufferSource(Source):
77
78
  self._ref = ref
78
79
  self._language_hint = language_hint
79
80
  self.edit_deltas: list[EditDelta] | None = edit_deltas
81
+ self._cache_snapshot = cache_snapshot
82
+ self._cached_old_content: str | None = None
80
83
 
81
84
  # ------------------------------------------------------------------
82
85
  # Source interface
@@ -88,10 +91,21 @@ class LiveBufferSource(Source):
88
91
  *old_content* is read from the committed blob at ``self._ref``.
89
92
  *new_content* is the in-memory buffer ``live_content``.
90
93
  """
91
- old_content = self._read_committed()
94
+ if self._cache_snapshot:
95
+ if self._cached_old_content is None:
96
+ self._cached_old_content = self._read_committed()
97
+ old_content = self._cached_old_content
98
+ else:
99
+ old_content = self._read_committed()
92
100
  filename = Path(self._file_path).name
93
101
  return old_content, self._live_content, filename, self._language_hint
94
102
 
103
+ def guardrail_policy_paths(self) -> tuple[str, str]:
104
+ """Use the selected repository, not process cwd, for buffer policy I/O."""
105
+ root = resolve_repo_root(self._repo_path)
106
+ path = str(safe_working_tree_path(root, self._file_path))
107
+ return path, path
108
+
95
109
  # ------------------------------------------------------------------
96
110
  # Internal helpers
97
111
  # ------------------------------------------------------------------
@@ -107,7 +121,33 @@ class LiveBufferSource(Source):
107
121
  data = run_git_bytes(
108
122
  root, ["cat-file", "blob", f"{self._ref}:{self._file_path}"]
109
123
  )
110
- except subprocess.CalledProcessError:
111
- # File not yet tracked at this ref — treat old side as empty.
124
+ except subprocess.CalledProcessError as exc:
125
+ # A missing file at a valid ref is a legitimate addition. An invalid
126
+ # ref or a missing/corrupted tracked blob is not: returning an empty
127
+ # baseline for either would manufacture a successful semantic diff
128
+ # against the wrong source (#229). Check the Git tree independently.
129
+ #
130
+ # Use a literal pathspec and -z output: glob characters, spaces and
131
+ # non-ASCII path bytes must not turn a tracked file into an addition.
132
+ entries = run_git_bytes(
133
+ root,
134
+ [
135
+ "ls-tree", "-r", "-z", "--full-tree",
136
+ self._ref, "--", f":(literal){self._file_path}",
137
+ ],
138
+ )
139
+ expected_path = self._file_path.encode("utf-8", errors="surrogateescape")
140
+ tracked = any(
141
+ entry.partition(b"\t")[2] == expected_path
142
+ for entry in entries.split(b"\0")
143
+ if entry
144
+ )
145
+ if tracked:
146
+ raise RuntimeError(
147
+ f"Failed to read tracked Git blob {self._ref}:{self._file_path}"
148
+ ) from exc
112
149
  return ""
113
- return data.decode("utf-8", errors="replace")
150
+ # Git can return a tracked blob whose bytes are not valid UTF-8.
151
+ # Replacing invalid bytes would invent an old source and falsely
152
+ # certify a semantic review against content Git never stored (#231).
153
+ return data.decode("utf-8")
@@ -1,126 +1,53 @@
1
- """
2
- intentumdiff.sources.patch_source
3
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
-
5
- Reconstruct old/new content from a unified diff patch string.
6
-
7
- Typical use-case: diffing an LLM-generated patch (e.g. GitHub Copilot output)
8
- without access to the original file.
1
+ """Thin source adapter for Rust-owned unified patch reconstruction.
9
2
 
10
- The patch must follow the unified diff format (``--- a/...`` / ``+++ b/...``).
11
- ``unidiff`` (third-party) is used for robust parsing.
3
+ With original content, every hunk is validated at its declared position. Without
4
+ it, a regular modification can only reconstruct a contiguous excerpt, which is
5
+ explicitly warned and exposed through ``is_partial``. Set ``require_complete``
6
+ to reject excerpts. Unknown prefixes/gaps and multi-file patches are rejected.
12
7
  """
13
-
14
8
  from __future__ import annotations
15
9
 
16
- import io
17
- from pathlib import PurePosixPath
18
-
19
- from unidiff import PatchSet
10
+ import json
11
+ import warnings
12
+ from typing import Any
20
13
 
21
14
  from intentumdiff.sources.base import Source
22
15
 
23
16
 
24
- def _apply_patch_to_original(original: str, patch_text: str) -> str:
25
- """
26
- Reconstruct the patched (new) content by applying hunks from a unified diff.
27
-
28
- We do a line-based apply; this is intentionally simple — we are not a full
29
- ``patch`` utility. For complex patches (binary, context mismatch) an
30
- error is raised.
31
- """
32
- patchset = PatchSet(io.StringIO(patch_text))
33
- if not patchset:
34
- return original
35
-
36
- patched_file = patchset[0] # we support single-file patches here
37
- old_lines = original.splitlines(keepends=True)
38
- new_lines: list[str] = []
39
- old_idx = 0 # 1-based line cursor
40
-
41
- for hunk in patched_file:
42
- # Copy context lines before this hunk
43
- hunk_start = hunk.source_start # 1-based
44
- while old_idx < hunk_start - 1:
45
- new_lines.append(old_lines[old_idx])
46
- old_idx += 1
47
-
48
- for line in hunk:
49
- if line.is_context:
50
- new_lines.append(old_lines[old_idx])
51
- old_idx += 1
52
- elif line.is_added:
53
- new_lines.append(line.value)
54
- elif line.is_removed:
55
- old_idx += 1 # skip removed original line
56
-
57
- # Trailing context
58
- while old_idx < len(old_lines):
59
- new_lines.append(old_lines[old_idx])
60
- old_idx += 1
61
-
62
- return "".join(new_lines)
63
-
64
-
65
- def _extract_filename(patch_text: str) -> str:
66
- """Extract the target filename from the ``+++`` header of a patch."""
67
- for line in patch_text.splitlines():
68
- if line.startswith("+++ "):
69
- raw = line[4:].strip()
70
- # Strip leading "b/" git prefix
71
- path = raw[2:] if raw.startswith("b/") else raw
72
- return path
73
- return "unknown"
17
+ class PatchExcerptWarning(UserWarning):
18
+ """The patch does not establish complete original-file content."""
74
19
 
75
20
 
76
21
  class PatchSource(Source):
77
- """
78
- Reconstruct old and new content from a unified diff patch.
22
+ """Reconstruct one text file with the shared Rust engine.
79
23
 
80
- Parameters
81
- ----------
82
- patch_text:
83
- Full unified diff string (as produced by ``git diff``, GitHub Copilot,
84
- or similar tools).
85
- original_content:
86
- The original (old) file content. If omitted, the old content is
87
- reconstructed from the patch's ``-`` lines (best-effort).
88
- language_hint:
89
- Optional language override.
90
- filename:
91
- Display filename. If omitted, extracted from the ``+++`` header.
24
+ ``original_content`` provides the complete base. Without it, creation/deletion
25
+ patches can establish complete content; regular patches yield an explicitly
26
+ labelled excerpt. ``filename`` and ``language_hint`` are optional overrides.
92
27
  """
93
-
94
- def __init__(
95
- self,
96
- patch_text: str,
97
- original_content: str | None = None,
98
- language_hint: str | None = None,
99
- filename: str | None = None,
100
- ) -> None:
101
- self._patch_text = patch_text
102
- self._original = original_content
28
+ def __init__(self, patch_text: str, original_content: str | None = None,
29
+ language_hint: str | None = None, filename: str | None = None,
30
+ *, require_complete: bool = False) -> None:
31
+ self._request = {"patch_text": patch_text, "original_content": original_content,
32
+ "filename": filename, "require_complete": require_complete}
103
33
  self._language_hint = language_hint
104
- self._filename = filename or _extract_filename(patch_text)
34
+ self._result: dict[str, Any] | None = None
35
+ self._warned = False
105
36
 
106
- def get_content(self) -> tuple[str, str, str, str | None]:
107
- if self._original is not None:
108
- old_content = self._original
109
- else:
110
- old_content = self._reconstruct_original()
37
+ def _content(self) -> dict[str, Any]:
38
+ if self._result is None:
39
+ from intentumdiff.rust_core import _c_abi_call
40
+ self._result = _c_abi_call("reconstruct_patch", json.dumps(self._request))
41
+ return self._result
111
42
 
112
- new_content = _apply_patch_to_original(old_content, self._patch_text)
113
- return old_content, new_content, self._filename, self._language_hint
43
+ @property
44
+ def is_partial(self) -> bool:
45
+ """Whether Rust identified the reconstructed content as an excerpt."""
46
+ return self._content()["scope"] == "excerpt"
114
47
 
115
- def _reconstruct_original(self) -> str:
116
- """Build the original content from ``-`` and context lines in the patch."""
117
- lines: list[str] = []
118
- for line in self._patch_text.splitlines(keepends=True):
119
- if line.startswith("---") or line.startswith("+++") or line.startswith("@@"):
120
- continue
121
- if line.startswith("-"):
122
- lines.append(line[1:])
123
- elif line.startswith(" "):
124
- lines.append(line[1:])
125
- # Lines starting with '+' are new — skip them
126
- return "".join(lines)
48
+ def get_content(self) -> tuple[str, str, str, str | None]:
49
+ result = self._content()
50
+ if result["warning"] and not self._warned:
51
+ warnings.warn(result["warning"], PatchExcerptWarning, stacklevel=2)
52
+ self._warned = True
53
+ return result["old_content"], result["new_content"], result["filename"], self._language_hint
@@ -48,3 +48,10 @@ def safe_working_tree_path(root: str | Path, file_path: str) -> Path:
48
48
  f"Unsafe file path: {file_path!r} - resolved path escapes {root_path!s}."
49
49
  ) from None
50
50
  return candidate
51
+
52
+
53
+ def safe_policy_path(root: str | Path, file_path: str) -> str:
54
+ """Locate policy context for a repository blob without following its live leaf."""
55
+ relative = Path(safe_relative_path(file_path))
56
+ parent = safe_working_tree_path(root, str(relative.parent))
57
+ return str(parent / relative.name)
intentumdiff/vcs/base.py CHANGED
@@ -115,6 +115,12 @@ class VcsBackend(ABC):
115
115
  # Future: semantic-merge hooks (non-abstract stubs)
116
116
  # ------------------------------------------------------------------
117
117
 
118
+ def guardrail_policy_path(self, path: str) -> str:
119
+ """Physical policy context for a backend-relative historical file."""
120
+ from intentumdiff.vcs._safe_path import safe_policy_path
121
+
122
+ return safe_policy_path(self.resolve_root(), path)
123
+
118
124
  def get_merge_base(self, ref_a: str, ref_b: str) -> str: # pragma: no cover
119
125
  """Return the common ancestor revision of *ref_a* and *ref_b*.
120
126
 
@@ -71,7 +71,7 @@ class GitVcsBackend(VcsBackend):
71
71
  """Return the on-disk content of *path* in the working tree."""
72
72
  full_path = safe_working_tree_path(self._root, _safe_path(path))
73
73
  try:
74
- return full_path.read_text(encoding="utf-8", errors="replace")
74
+ return full_path.read_text(encoding="utf-8", errors="strict")
75
75
  except FileNotFoundError:
76
76
  return ""
77
77