intentumdiff-python 0.0.1__py3-none-win_amd64.whl → 0.0.3b1__py3-none-win_amd64.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
@@ -35,6 +35,14 @@ class GitHubAppReviewResult:
35
35
  summary_markdown: str
36
36
  html_report: str
37
37
 
38
+ def __post_init__(self) -> None:
39
+ for name in ("checked_files", "semantic_changes", "guardrail_violations"):
40
+ value = getattr(self, name)
41
+ if type(value) is not int or value < 0:
42
+ raise GitHubAppError(f"Review {name} must be a non-negative integer")
43
+ if type(self.passed) is not bool:
44
+ raise GitHubAppError("Review passed must be a boolean")
45
+
38
46
 
39
47
  def verify_webhook_signature(secret: str, body: bytes, signature_header: str | None) -> bool:
40
48
  """Return True when *signature_header* matches GitHub's sha256 HMAC."""
@@ -42,7 +50,7 @@ def verify_webhook_signature(secret: str, body: bytes, signature_header: str | N
42
50
  if not secret or not signature_header or not signature_header.startswith("sha256="):
43
51
  return False
44
52
  expected = "sha256=" + hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
45
- return hmac.compare_digest(expected, signature_header)
53
+ return hmac.compare_digest(expected.encode("ascii"), signature_header.encode("utf-8"))
46
54
 
47
55
 
48
56
  def parse_pull_request_url(url: str) -> PullRequestRef:
@@ -86,16 +94,13 @@ def parse_pull_request_event(payload: Mapping[str, Any]) -> PullRequestRef:
86
94
  full_name = str(repository.get("full_name") or "")
87
95
  if "/" not in full_name:
88
96
  raise GitHubAppError("Webhook repository.full_name must be OWNER/REPO")
89
- number = pull_request.get("number") or payload.get("number")
90
- try:
91
- pr_number = int(number)
92
- except (TypeError, ValueError) as exc:
93
- raise GitHubAppError("Webhook pull request number must be an integer") from exc
97
+ pr_number = pull_request.get("number") or payload.get("number")
98
+ # Exact int only: int() coerced True and 1.5 to pull request 1 (#322); bool is excluded.
99
+ if type(pr_number) is not int or pr_number <= 0:
100
+ raise GitHubAppError("Webhook pull request number must be a positive integer")
94
101
  owner, repo = full_name.split("/", 1)
95
102
  if not owner or not repo:
96
103
  raise GitHubAppError("Webhook repository.full_name must be OWNER/REPO")
97
- if pr_number <= 0:
98
- raise GitHubAppError("Webhook pull request number must be positive")
99
104
  return PullRequestRef(owner=owner, repo=repo, number=pr_number)
100
105
 
101
106
 
@@ -107,6 +112,8 @@ def build_check_run_payload(
107
112
  passed: bool,
108
113
  details_url: str | None = None,
109
114
  ) -> dict[str, Any]:
115
+ if type(passed) is not bool:
116
+ raise GitHubAppError("Review passed must be a boolean")
110
117
  conclusion = "success" if passed else "failure"
111
118
  payload: dict[str, Any] = {
112
119
  "name": name,
@@ -124,15 +131,23 @@ def build_check_run_payload(
124
131
 
125
132
 
126
133
  def build_review_result_from_payload(payload: Mapping[str, Any]) -> GitHubAppReviewResult:
127
- """Build deterministic local review artifacts from injectable webhook payload data."""
134
+ """Render explicit review evidence; never infer a successful engine result."""
128
135
 
129
136
  review = payload.get("intentumdiff_review")
130
137
  if not isinstance(review, Mapping):
131
- review = {}
132
- checked_files = _non_negative_int(review.get("checked_files"), default=0)
133
- semantic_changes = _non_negative_int(review.get("semantic_changes"), default=0)
134
- guardrail_violations = _non_negative_int(review.get("guardrail_violations"), default=0)
135
- passed = bool(review.get("passed", semantic_changes == 0 and guardrail_violations == 0))
138
+ raise GitHubAppError("Explicit intentumdiff_review evidence is required")
139
+ evidence = GitHubAppReviewResult(
140
+ checked_files=review.get("checked_files"),
141
+ semantic_changes=review.get("semantic_changes"),
142
+ guardrail_violations=review.get("guardrail_violations"),
143
+ passed=review.get("passed"),
144
+ summary_markdown="",
145
+ html_report="",
146
+ )
147
+ checked_files = evidence.checked_files
148
+ semantic_changes = evidence.semantic_changes
149
+ guardrail_violations = evidence.guardrail_violations
150
+ passed = evidence.passed
136
151
  summary_markdown = render_github_app_summary(
137
152
  checked_files=checked_files,
138
153
  semantic_changes=semantic_changes,
@@ -251,14 +266,6 @@ def decode_webhook_body(body: bytes) -> dict[str, Any]:
251
266
  return payload
252
267
 
253
268
 
254
- def _non_negative_int(value: Any, *, default: int) -> int:
255
- try:
256
- parsed = int(value)
257
- except (TypeError, ValueError):
258
- return default
259
- return max(parsed, 0)
260
-
261
-
262
269
  def create_app() -> Any:
263
270
  """Create the optional FastAPI app without making FastAPI a core dependency."""
264
271
 
@@ -276,12 +283,18 @@ def create_app() -> Any:
276
283
  x_hub_signature_256: str | None = Header(default=None),
277
284
  ) -> dict[str, Any]:
278
285
  body = await request.body()
279
- secret = request.app.state.webhook_secret if hasattr(request.app.state, "webhook_secret") else ""
280
- if secret and not verify_webhook_signature(secret, body, x_hub_signature_256):
286
+ # A missing signing key must never disable authentication by accident.
287
+ secret = getattr(request.app.state, "webhook_secret", None)
288
+ if not isinstance(secret, str) or not secret:
289
+ raise HTTPException(status_code=503, detail="webhook signing secret not configured")
290
+ if not verify_webhook_signature(secret, body, x_hub_signature_256):
281
291
  raise HTTPException(status_code=401, detail="invalid signature")
282
- payload = decode_webhook_body(body)
283
- if x_github_event == "pull_request":
284
- return build_pull_request_check_response(payload)
292
+ try:
293
+ payload = decode_webhook_body(body)
294
+ if x_github_event == "pull_request":
295
+ return build_pull_request_check_response(payload)
296
+ except (GitHubAppError, UnicodeDecodeError, json.JSONDecodeError) as exc:
297
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
285
298
  return {"ok": True, "event": x_github_event}
286
299
 
287
300
  return app
@@ -80,7 +80,7 @@ if TYPE_CHECKING:
80
80
  from intentumdiff.differ import SemanticDiffer
81
81
  from rich.console import Console as RichConsole
82
82
 
83
- from intentumdiff.core.models import ChangeStreamEvent, EditDelta
83
+ from intentumdiff.core.models import ChangeStreamEvent, ChangeStreamPhase, EditDelta
84
84
  from intentumdiff.sources.live_buffer_source import LiveBufferSource
85
85
 
86
86
  logger = logging.getLogger(__name__)
@@ -124,6 +124,14 @@ class _ParsedRequest:
124
124
  stream: bool | None = None
125
125
 
126
126
 
127
+ class _RustLiveDecline(RuntimeError):
128
+ """Transport the Rust Core's typed incomplete-result response unchanged."""
129
+
130
+ def __init__(self, code: str, message: str) -> None:
131
+ super().__init__(message)
132
+ self.code = code
133
+
134
+
127
135
  def _make_socket_dir() -> str:
128
136
  """Return (and create) a private directory for the server's socket file."""
129
137
  runtime_dir = os.environ.get("XDG_RUNTIME_DIR", "")
@@ -144,10 +152,37 @@ def _make_socket_dir() -> str:
144
152
  return sock_dir
145
153
 
146
154
 
155
+ # AF_UNIX addresses are a fixed-size struct field, not a string: sun_path is 104 bytes on
156
+ # macOS and 108 on Linux, INCLUDING the NUL. Exceeding it raises "AF_UNIX path too long" at
157
+ # bind() - not at connect, so the server simply never starts.
158
+ #
159
+ # macOS makes this easy to hit without doing anything unusual: TMPDIR there is a per-session
160
+ # path like /var/folders/xy/9k4n.../T/, and this module then adds a per-pid directory and a
161
+ # 16-character token. A GitHub macOS runner blows the limit outright, and so does any user
162
+ # whose temp path is a little long.
163
+ _SUN_PATH_MAX = 104 if sys.platform == "darwin" else 108
164
+
165
+
147
166
  def _make_socket_path(pid: int, token: str) -> str:
148
- """Return a private socket path incorporating a random token."""
149
- sock_dir = _make_socket_dir()
150
- return os.path.join(sock_dir, f"intentumdiff-live-{token[:16]}.sock")
167
+ """Return a private socket path incorporating a random token.
168
+
169
+ Falls back to a shorter base if the preferred path would not fit in sun_path. The
170
+ fallback keeps the security properties that matter - an owner-only directory and an
171
+ unguessable name - and trades only the length of the token.
172
+ """
173
+ path = os.path.join(_make_socket_dir(), f"intentumdiff-live-{token[:16]}.sock")
174
+ if len(os.fsencode(path)) < _SUN_PATH_MAX:
175
+ return path
176
+
177
+ # Shortest base that is private per user and short on every POSIX system we support.
178
+ short = os.path.join(tempfile.gettempdir() if len(tempfile.gettempdir()) < 12 else "/tmp",
179
+ f"imd-{pid}")
180
+ os.makedirs(short, mode=0o700, exist_ok=True) # nosemgrep: python.lang.security.audit.insecure-file-permissions.insecure-file-permissions
181
+ try:
182
+ os.chmod(short, 0o700) # nosemgrep: python.lang.security.audit.insecure-file-permissions.insecure-file-permissions
183
+ except OSError:
184
+ pass
185
+ return os.path.join(short, f"{token[:8]}.sock")
151
186
 
152
187
 
153
188
  def _has_unix_socket() -> bool:
@@ -292,19 +327,12 @@ if sys.platform == "win32": # pragma: no cover
292
327
  DACL when the module-level struct could not be built.
293
328
  """
294
329
  handle = ctypes.windll.kernel32.CreateNamedPipeW(
295
- name,
296
- _PIPE_ACCESS_DUPLEX,
297
- _PIPE_TYPE_BYTE | _PIPE_WAIT,
298
- _PIPE_UNLIMITED_INSTANCES,
299
- 65536,
300
- 65536,
301
- 0,
330
+ name, _PIPE_ACCESS_DUPLEX, _PIPE_TYPE_BYTE | _PIPE_WAIT, _PIPE_UNLIMITED_INSTANCES,
331
+ 65536, 65536, 0,
302
332
  ctypes.byref(_pipe_sa) if _pipe_sa is not None else None, # type: ignore[name-defined]
303
333
  )
304
334
  if handle == _INVALID_HANDLE:
305
- raise OSError(
306
- f"CreateNamedPipeW failed (error {ctypes.GetLastError()})"
307
- )
335
+ raise OSError(f"CreateNamedPipeW failed (error {ctypes.GetLastError()})")
308
336
  return handle
309
337
 
310
338
  def _open_pipe_client(name: str) -> None:
@@ -351,9 +379,7 @@ if sys.platform == "win32": # pragma: no cover
351
379
  server stop-event is set."""
352
380
  avail = _wt.DWORD(0)
353
381
  while not self._stop_event.is_set():
354
- ok = _PeekNamedPipe(
355
- self._handle, None, 0, None, ctypes.byref(avail), None
356
- )
382
+ ok = _PeekNamedPipe(self._handle, None, 0, None, ctypes.byref(avail), None)
357
383
  if not ok:
358
384
  return b"" # pipe broken
359
385
  if avail.value > 0:
@@ -368,10 +394,9 @@ if sys.platform == "win32": # pragma: no cover
368
394
  return b"" # stop requested
369
395
 
370
396
  def sendall(self, data: bytes) -> None:
371
- n_written = _wt.DWORD(0)
372
- ctypes.windll.kernel32.WriteFile(
373
- self._handle, data, len(data), ctypes.byref(n_written), None
374
- )
397
+ n, kernel32 = _wt.DWORD(0), ctypes.windll.kernel32 # a failed WriteFile counts 0
398
+ _write_all(lambda chunk: kernel32.WriteFile(
399
+ self._handle, chunk, len(chunk), ctypes.byref(n), None) and n.value, data)
375
400
 
376
401
  def close(self) -> None:
377
402
  if not self._closed:
@@ -734,7 +759,16 @@ class LiveServer:
734
759
  _write_line_bytes(conn, {"error": "request line too large"})
735
760
  buf = b""
736
761
  break
737
- line = line_bytes.decode("utf-8", errors="replace").strip()
762
+ try:
763
+ line = line_bytes.decode("utf-8", errors="strict").strip()
764
+ except UnicodeDecodeError:
765
+ _write_line_bytes(
766
+ conn,
767
+ self._error_response(
768
+ 0, "invalid_utf8", "Request line must be valid UTF-8"
769
+ ),
770
+ )
771
+ continue
738
772
  if not line:
739
773
  continue
740
774
  try:
@@ -905,9 +939,16 @@ class LiveServer:
905
939
  use_stream = self._stream_analysis if request.stream is None else request.stream
906
940
  try:
907
941
  if use_stream:
908
- for event in self._differ.diff_stream_progressive(source):
942
+ # Stream transport shares the SAME Rust-certified complete diff
943
+ # and typed decline contract as non-streaming. Emit only FINAL
944
+ # events from that result; never finalize a fallback as success.
945
+ diff = self._compute_diff(source, request)
946
+ for change in diff.changes:
909
947
  if self._is_stale(request):
910
948
  return
949
+ event = ChangeStreamEvent(
950
+ phase=ChangeStreamPhase.FINAL, action="add", change=change
951
+ )
911
952
  send_fn({
912
953
  "op": "diff",
913
954
  "seq": request.seq,
@@ -935,6 +976,8 @@ class LiveServer:
935
976
  "guardrail_violation_count": len(diff.guardrail_violations),
936
977
  },
937
978
  })
979
+ except _RustLiveDecline as exc:
980
+ send_fn(self._error_response(request.seq, exc.code, str(exc), op="diff"))
938
981
  except FileNotFoundError as exc:
939
982
  send_fn(
940
983
  self._error_response(
@@ -960,10 +1003,10 @@ class LiveServer:
960
1003
  ) -> Any:
961
1004
  """Return the ``SemanticDiff`` for a non-streaming request.
962
1005
 
963
- The native handler in the Rust core serves Python files end-to-end (certified batch,
964
- #100 A2.5 Phase A1); it returns the diff JSON, which is rebuilt through the DTO so
965
- normalisation matches the Python path exactly. Any other language, or a non-certified
966
- outcome, falls back to the Python differ pipeline unchanged.
1006
+ The Rust handler returns a certified diff DTO or a typed/legacy decline.
1007
+ Declines and fallback-marked/incomplete DTOs never become successful live
1008
+ semantic reviews. Explicit diagnostics may use the routed Rust pipeline,
1009
+ but its incomplete results are likewise rejected.
967
1010
  """
968
1011
  from intentumdiff import rust_core
969
1012
  from intentumdiff.core.models import SemanticDiff
@@ -980,9 +1023,47 @@ class LiveServer:
980
1023
  self._differ._config.model_dump_json(),
981
1024
  _wasm_dir(),
982
1025
  )
1026
+ if "fallback_code" in native:
1027
+ # Rust owns completeness: a typed decline is an error, never
1028
+ # permission to recover a purportedly successful Python diff.
1029
+ raise _RustLiveDecline(
1030
+ str(native["fallback_code"]),
1031
+ str(native.get("fallback") or "Rust Core declined an incomplete diff"),
1032
+ )
983
1033
  if "diff" in native:
984
- return SemanticDiff.model_validate(native["diff"])
985
- return self._differ.diff(source)
1034
+ # Validate raw Rust inventories and flags before Pydantic can
1035
+ # default omitted arrays/booleans into manufactured success.
1036
+ # This is the existing batch transport validator, not a
1037
+ # second Python semantic evaluator.
1038
+ try:
1039
+ rust_core._require_complete_batch_diff_dto(native["diff"])
1040
+ except (TypeError, ValueError) as exc:
1041
+ raise _RustLiveDecline(
1042
+ "native_diff_uncertified",
1043
+ f"{request.path}: malformed Rust Core live diff: {exc}",
1044
+ ) from exc
1045
+ diff = SemanticDiff.model_validate(native["diff"])
1046
+ if diff.is_fallback or diff.parse_errors:
1047
+ raise _RustLiveDecline(
1048
+ "native_parse_incomplete",
1049
+ f"{request.path}: Rust Core returned an incomplete diff "
1050
+ f"({'; '.join(diff.parse_errors) or 'source fallback'})",
1051
+ )
1052
+ return diff
1053
+ # A legacy untyped decline is NOT permission to turn an uncertified
1054
+ # native result into a successful Python-path semantic review.
1055
+ raise _RustLiveDecline(
1056
+ "native_diff_uncertified",
1057
+ f"{request.path}: {native.get('fallback') or 'Rust Core returned no certified diff'}",
1058
+ )
1059
+ diff = self._differ.diff(source)
1060
+ if diff.is_fallback or diff.parse_errors:
1061
+ raise _RustLiveDecline(
1062
+ "native_parse_incomplete",
1063
+ f"{request.path}: diagnostic diff is incomplete "
1064
+ f"({'; '.join(diff.parse_errors) or 'source fallback'})",
1065
+ )
1066
+ return diff
986
1067
 
987
1068
  def _compute_review(
988
1069
  self,
@@ -993,10 +1074,10 @@ class LiveServer:
993
1074
  ) -> Any:
994
1075
  """Return the ``CommitDiff`` for a non-streaming review.
995
1076
 
996
- The native handler serves all-Python certified commits from the core (#100 A2.5 Phase A2),
997
- returning the CommitDiff JSON (rebuilt through the DTO for parity); any other case (mixed
998
- language, working-tree review, diagnostics, or a non-certified batch) falls back to the
999
- Python ``CommitDiffer.diff_commit``.
1077
+ The Rust Core certifies the non-streamed commit review and Python only
1078
+ validates/transports its DTO. Native declines must not fall through to
1079
+ another success path. Explicit diagnostics use routed Rust-backed review;
1080
+ the final completeness check also applies to that result.
1000
1081
  """
1001
1082
  from intentumdiff import rust_core
1002
1083
  from intentumdiff.core.models import CommitDiff
@@ -1009,8 +1090,33 @@ class LiveServer:
1009
1090
  review_config.model_dump_json(),
1010
1091
  _wasm_dir(),
1011
1092
  )
1093
+ if "fallback_code" in native:
1094
+ raise _RustLiveDecline(
1095
+ str(native["fallback_code"]),
1096
+ str(native.get("fallback") or "Rust Core declined an incomplete commit review"),
1097
+ )
1012
1098
  if "commit_diff" in native:
1099
+ # Reuse the certified commit-byte contract. Validation happens
1100
+ # on the raw native object, before Pydantic can supply empty
1101
+ # file inventories or coerce malformed semantic flags.
1102
+ try:
1103
+ raw_commit = json.dumps(
1104
+ native["commit_diff"], separators=(",", ":")
1105
+ ).encode("utf-8")
1106
+ rust_core._require_native_commit_diff_json(raw_commit, "live review")
1107
+ except (rust_core._InvalidNativeCommitDto, TypeError, ValueError) as exc:
1108
+ raise _RustLiveDecline(
1109
+ "native_review_uncertified",
1110
+ f"{new_ref or 'working tree'}: malformed Rust Core live review: {exc}",
1111
+ ) from exc
1013
1112
  return CommitDiff.model_validate(native["commit_diff"])
1113
+ # A native refusal must not become a fabricated successful review
1114
+ # through a second, routed Python orchestration path.
1115
+ raise _RustLiveDecline(
1116
+ "native_review_uncertified",
1117
+ f"{new_ref or 'working tree'}: "
1118
+ f"{native.get('fallback') or 'Rust Core returned no certified commit review'}",
1119
+ )
1014
1120
  return commit_differ.diff_commit(
1015
1121
  repo_path=self._repo_path, old_ref=old_ref, new_ref=new_ref
1016
1122
  )
@@ -1047,9 +1153,40 @@ class LiveServer:
1047
1153
  if op == "cancel":
1048
1154
  send_fn(self._cancel_request(request, seq))
1049
1155
  return True
1050
- send_fn(self._error_response(seq, "unknown_op", f"unknown op: {op!r}", op=str(op)))
1156
+ if op == "asset_diff":
1157
+ send_fn(self._asset_diff_request(request, seq))
1158
+ return True
1159
+ # `invalid_op`, not `unknown_op`: the native server has always answered an unrouted op
1160
+ # with that code, and it is the spelling the extension lists as non-retryable — so the
1161
+ # python server's own spelling made the extension auto-retry a request that can never
1162
+ # succeed. Two servers on one protocol have to name the same failure the same way.
1163
+ send_fn(self._error_response(seq, "invalid_op", f"unknown op: {op!r}", op=str(op)))
1051
1164
  return True
1052
1165
 
1166
+ def _asset_diff_request(self, request: dict[str, Any], seq: int) -> dict[str, Any]:
1167
+ """Perceptual image diff — the engine does the pixel work, this only marshals the request.
1168
+
1169
+ The extension previously synthesised an asset "review" and never asked for artifacts,
1170
+ so the panel always reported PERCEPTUAL DIFF PENDING while the engine sat there able
1171
+ to answer. This is the missing call.
1172
+
1173
+ Two request shapes, both engine-served:
1174
+
1175
+ * ``path`` (+ optional ``ref``) — one tracked image against a git ref. This is what a
1176
+ reviewing editor has: a repo-relative path and a base. The *before* bytes are in the
1177
+ object store, and materialising them is git work, so the engine does it.
1178
+ * ``before_path`` + ``after_path`` — two files that already exist on disk.
1179
+
1180
+ Request parsing, the path-containment guard and the self-ignoring artifact cache live in
1181
+ the core's ``live_handle_asset_diff``, so this server and the native live-server binary
1182
+ answer from ONE implementation. A second copy here would be a second place for the
1183
+ containment rule to drift — and the rule is what stops a protocol method that accepts
1184
+ file paths from becoming an arbitrary-file reader.
1185
+ """
1186
+ from intentumdiff import rust_core
1187
+
1188
+ return rust_core.live_handle_asset_diff(self._repo_path, self._ref, request, seq)
1189
+
1053
1190
  def _process_review_request(
1054
1191
  self,
1055
1192
  request: dict[str, Any],
@@ -1100,6 +1237,20 @@ class LiveServer:
1100
1237
  commit_diff = self._compute_review(
1101
1238
  review_config, commit_differ, old_ref, new_ref
1102
1239
  )
1240
+ # Streamed file events are provisional. Rust's completeness flags
1241
+ # must be checked before publishing an ok:true whole-commit result.
1242
+ incomplete_files = [
1243
+ f"{item.new_filename or item.old_filename}: "
1244
+ f"{'; '.join(item.parse_errors) or 'source fallback'}"
1245
+ for item in commit_diff.file_diffs
1246
+ if item.is_fallback or item.parse_errors
1247
+ ]
1248
+ if commit_diff.parse_errors or incomplete_files:
1249
+ raise _RustLiveDecline(
1250
+ "native_parse_incomplete",
1251
+ "Incomplete commit review: "
1252
+ + "; ".join([*commit_diff.parse_errors, *incomplete_files]),
1253
+ )
1103
1254
  with self._lock:
1104
1255
  if seq < self._latest_review_seq:
1105
1256
  return
@@ -1123,6 +1274,8 @@ class LiveServer:
1123
1274
  })
1124
1275
  except _ReviewCancelled:
1125
1276
  return
1277
+ except _RustLiveDecline as exc:
1278
+ send_fn(self._error_response(seq, exc.code, str(exc), op="review"))
1126
1279
  except Exception as exc:
1127
1280
  logger.warning(
1128
1281
  "LiveServer review error for seq=%d: %s",
@@ -1305,6 +1458,16 @@ def _write_line(stream: "Any", obj: dict[str, Any]) -> None:
1305
1458
  pass
1306
1459
 
1307
1460
 
1461
+ def _write_all(write: Any, data: bytes) -> None:
1462
+ """Send all of *data* via ``write(chunk) -> bytes written`` (0 = failed), or raise (#327)."""
1463
+ view = memoryview(data)
1464
+ while view:
1465
+ written = write(bytes(view))
1466
+ if not written: # WriteFile failed, or wrote nothing: the peer is gone
1467
+ raise BrokenPipeError("named-pipe write failed before the whole response was sent")
1468
+ view = view[written:]
1469
+
1470
+
1308
1471
  def _write_line_bytes(sock: socket.socket, obj: dict[str, Any]) -> None:
1309
1472
  """Write *obj* as a JSON line to a socket."""
1310
1473
  try:
@@ -175,7 +175,11 @@ class AsyncLspClient:
175
175
  await self._cleanup_start_failure()
176
176
  raise
177
177
  except asyncio.CancelledError as exc:
178
- # The server closed its connection during the initialize handshake.
178
+ current = asyncio.current_task()
179
+ if current is not None and current.cancelling(): # the caller cancelled: keep that
180
+ await self._cleanup_start_failure()
181
+ raise
182
+ # Otherwise the server closed its connection during the initialize handshake.
179
183
  # Yield once so _drain_stderr can read any buffered output.
180
184
  await asyncio.sleep(0)
181
185
  hint = self._stderr_hint()
@@ -194,24 +198,27 @@ class AsyncLspClient:
194
198
  logger.debug("LSP client connected to %s", self._config)
195
199
 
196
200
  async def _cleanup_start_failure(self) -> None:
197
- """Cancel reader task and release resources after a failed :meth:`start`."""
198
- if self._stderr_task is not None:
199
- self._stderr_task.cancel()
200
- with suppress(Exception):
201
- await self._stderr_task
202
- self._stderr_task = None
203
- if self._reader_task is not None:
204
- self._reader_task.cancel()
205
- with suppress(Exception):
206
- await self._reader_task
207
- self._reader_task = None
208
- if self._writer is not None:
209
- with suppress(Exception):
210
- self._writer.close()
211
- if self._process is not None:
212
- with suppress(Exception):
213
- self._process.terminate()
214
- self._process = None
201
+ """Release every resource a failed :meth:`start` owns, even when cancelled (#313).
202
+
203
+ Awaiting a cancelled task raises CancelledError, a BaseException, which used to escape
204
+ ``suppress(Exception)`` before the writer was closed and the process was terminated.
205
+ """
206
+ tasks = [task for task in (self._stderr_task, self._reader_task) if task is not None]
207
+ self._stderr_task = self._reader_task = None
208
+ process, self._process = self._process, None
209
+ for task in tasks:
210
+ task.cancel()
211
+ try:
212
+ await asyncio.gather(*tasks, return_exceptions=True)
213
+ finally:
214
+ if self._writer is not None:
215
+ with suppress(Exception):
216
+ self._writer.close()
217
+ if process is not None:
218
+ with suppress(ProcessLookupError):
219
+ process.kill() # it never finished initialize; reap it
220
+ with suppress(Exception):
221
+ await asyncio.wait_for(process.wait(), timeout=3.0)
215
222
 
216
223
  async def _start_tcp(self) -> None:
217
224
  """Establish a TCP connection to an already-running server."""
@@ -374,6 +381,7 @@ class AsyncLspClient:
374
381
  "rootUri": self._root_uri,
375
382
  "workspaceFolders": [{"uri": self._root_uri, "name": "workspace"}],
376
383
  "capabilities": {
384
+ "general": {"positionEncodings": ["utf-16"]},
377
385
  "textDocument": {
378
386
  "hover": {
379
387
  "contentFormat": ["plaintext", "markdown"],
@@ -385,7 +393,12 @@ class AsyncLspClient:
385
393
  },
386
394
  "clientInfo": {"name": "IntentumDiff", "version": "0.1"},
387
395
  }
388
- await self._send_request("initialize", init_params)
396
+ result = await self._send_request("initialize", init_params)
397
+ if not isinstance(result, dict) or not isinstance(result.get("capabilities", {}), dict):
398
+ raise LspConnectionError("Invalid LSP initialize capabilities")
399
+ encoding = result.get("capabilities", {}).get("positionEncoding", "utf-16")
400
+ if encoding != "utf-16":
401
+ raise LspConnectionError(f"Unsupported LSP position encoding: {encoding}")
389
402
  self._send_notification("initialized", {})
390
403
 
391
404
  def _next_request_id(self) -> int:
@@ -405,31 +418,24 @@ class AsyncLspClient:
405
418
 
406
419
  async def _send_request(self, method: str, params: Any) -> Any:
407
420
  rid = self._next_request_id()
408
- loop = asyncio.get_running_loop()
409
- fut: asyncio.Future[Any] = loop.create_future()
421
+ fut: asyncio.Future[Any] = asyncio.get_running_loop().create_future()
410
422
  self._pending[rid] = fut
411
- self._send_raw(_request(method, params, rid))
412
- # Drain the write buffer
413
- writer = self._writer
414
- if writer is None:
415
- self._pending.pop(rid, None)
416
- raise LspConnectionError(f"LSP client for {self._config} is not connected")
417
- try:
418
- await asyncio.wait_for(writer.drain(), timeout=self._timeout)
419
- except asyncio.TimeoutError as exc:
420
- self._pending.pop(rid, None)
421
- raise LspTimeoutError(
422
- f"Write timeout sending {method!r} to {self._config}"
423
- ) from exc
424
- try:
425
- return await asyncio.wait_for(
426
- asyncio.shield(fut), timeout=self._timeout
427
- )
428
- except asyncio.TimeoutError as exc:
423
+ try: # the registration never outlives this call, however it ends (#313)
424
+ self._send_raw(_request(method, params, rid)) # raises when not connected
425
+ writer: Any = self._writer
426
+ try:
427
+ await asyncio.wait_for(writer.drain(), timeout=self._timeout)
428
+ except asyncio.TimeoutError as exc:
429
+ message = f"Write timeout sending {method!r} to {self._config}"
430
+ raise LspTimeoutError(message) from exc
431
+ try:
432
+ return await asyncio.wait_for(asyncio.shield(fut), timeout=self._timeout)
433
+ except asyncio.TimeoutError as exc:
434
+ raise LspTimeoutError(
435
+ f"No response to {method!r} from {self._config} within {self._timeout}s"
436
+ ) from exc
437
+ finally:
429
438
  self._pending.pop(rid, None)
430
- raise LspTimeoutError(
431
- f"No response to {method!r} from {self._config} within {self._timeout}s"
432
- ) from exc
433
439
 
434
440
  async def _drain_stderr(self) -> None:
435
441
  """Background task: drain subprocess stderr into a capped ring buffer."""