intentumdiff-python 0.0.1__py3-none-manylinux_2_39_x86_64.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.
- intentumdiff/__init__.py +134 -0
- intentumdiff/_differ_gate.py +210 -0
- intentumdiff/_differ_presentation.py +786 -0
- intentumdiff/_differ_runtime.py +320 -0
- intentumdiff/analysis/__init__.py +1 -0
- intentumdiff/analysis/compile_commands.py +151 -0
- intentumdiff/analysis/cross_file.py +71 -0
- intentumdiff/analysis/diagnostics.py +309 -0
- intentumdiff/analysis/guardrail_reports.py +254 -0
- intentumdiff/analysis/guardrails.py +318 -0
- intentumdiff/analysis/invariances.py +1207 -0
- intentumdiff/analysis/keyed_profiles.py +25 -0
- intentumdiff/analysis/resource_profiles.py +14 -0
- intentumdiff/analysis/schema_resolver.py +816 -0
- intentumdiff/analysis/text_review.py +46 -0
- intentumdiff/analysis/user_schemas.py +430 -0
- intentumdiff/assets.py +45 -0
- intentumdiff/cache/__init__.py +37 -0
- intentumdiff/cache/duckdb_store.py +98 -0
- intentumdiff/cache/sqlite_store.py +149 -0
- intentumdiff/cache/store.py +190 -0
- intentumdiff/cli/__init__.py +199 -0
- intentumdiff/cli/_commands.py +2141 -0
- intentumdiff/cli/_parser.py +1061 -0
- intentumdiff/cli/_shared.py +644 -0
- intentumdiff/content_type.py +59 -0
- intentumdiff/core/__init__.py +1 -0
- intentumdiff/core/commit_differ.py +599 -0
- intentumdiff/core/config.py +51 -0
- intentumdiff/core/cst_serializer.py +101 -0
- intentumdiff/core/diffignore.py +87 -0
- intentumdiff/core/index.py +189 -0
- intentumdiff/core/indexer.py +792 -0
- intentumdiff/core/models.py +837 -0
- intentumdiff/differ.py +2195 -0
- intentumdiff/github_app.py +287 -0
- intentumdiff/intentumdiff_rust_core/__init__.py +7 -0
- intentumdiff/intentumdiff_rust_core/ffi.py +8 -0
- intentumdiff/intentumdiff_rust_core/libintentumdiff_rust_core.so +0 -0
- intentumdiff/invariances/__init__.py +2 -0
- intentumdiff/invariances/rules.schema.json +283 -0
- intentumdiff/invariances/rules.yaml +349 -0
- intentumdiff/live_server.py +1314 -0
- intentumdiff/lsp/__init__.py +67 -0
- intentumdiff/lsp/client.py +544 -0
- intentumdiff/lsp/config.py +96 -0
- intentumdiff/lsp/enricher.py +227 -0
- intentumdiff/lsp/exceptions.py +27 -0
- intentumdiff/lsp/launcher.py +273 -0
- intentumdiff/lsp/servers.py +356 -0
- intentumdiff/lsp_server/__init__.py +14 -0
- intentumdiff/lsp_server/_codelens.py +67 -0
- intentumdiff/lsp_server/_diagnostics.py +62 -0
- intentumdiff/lsp_server/_handlers.py +175 -0
- intentumdiff/lsp_server/server.py +205 -0
- intentumdiff/plugins/__init__.py +1 -0
- intentumdiff/plugins/adapter.py +397 -0
- intentumdiff/plugins/builtins.py +323 -0
- intentumdiff/plugins/exceptions.py +93 -0
- intentumdiff/plugins/hub.py +1155 -0
- intentumdiff/plugins/language_metadata.py +250 -0
- intentumdiff/plugins/loader.py +1252 -0
- intentumdiff/plugins/registry.py +1079 -0
- intentumdiff/plugins/registry.schema.json +99 -0
- intentumdiff/plugins/registry_schema.py +280 -0
- intentumdiff/plugins/wit/plugin.wit +351 -0
- intentumdiff/rust_core.py +2370 -0
- intentumdiff/serve/__init__.py +19 -0
- intentumdiff/serve/_app.py +485 -0
- intentumdiff/serve/_static/index.html +326 -0
- intentumdiff/serve/_static/playground.js +567 -0
- intentumdiff/sources/__init__.py +1 -0
- intentumdiff/sources/base.py +28 -0
- intentumdiff/sources/file_source.py +48 -0
- intentumdiff/sources/git_source.py +375 -0
- intentumdiff/sources/live_buffer_source.py +113 -0
- intentumdiff/sources/patch_source.py +126 -0
- intentumdiff/sources/string_source.py +44 -0
- intentumdiff/testing.py +165 -0
- intentumdiff/vcs/__init__.py +37 -0
- intentumdiff/vcs/_safe_path.py +50 -0
- intentumdiff/vcs/base.py +136 -0
- intentumdiff/vcs/git_backend.py +97 -0
- intentumdiff/vcs/git_cli.py +100 -0
- intentumdiff/vcs/hg_backend.py +94 -0
- intentumdiff/vcs/perforce_backend.py +109 -0
- intentumdiff/vcs/svn_backend.py +105 -0
- intentumdiff/wasm/.gitkeep +2 -0
- intentumdiff/wasm/abap_parser.wasm +0 -0
- intentumdiff/wasm/adf_parser.wasm +0 -0
- intentumdiff/wasm/asciidoc_parser.wasm +0 -0
- intentumdiff/wasm/asm_parser.wasm +0 -0
- intentumdiff/wasm/assemblyscript_parser.wasm +0 -0
- intentumdiff/wasm/astro_parser.wasm +0 -0
- intentumdiff/wasm/bash_parser.wasm +0 -0
- intentumdiff/wasm/clojure_parser.wasm +0 -0
- intentumdiff/wasm/cmake_parser.wasm +0 -0
- intentumdiff/wasm/cpp_parser.wasm +0 -0
- intentumdiff/wasm/csharp_parser.wasm +0 -0
- intentumdiff/wasm/css_parser.wasm +0 -0
- intentumdiff/wasm/dart_parser.wasm +0 -0
- intentumdiff/wasm/databricks_parser.wasm +0 -0
- intentumdiff/wasm/dax_parser.wasm +0 -0
- intentumdiff/wasm/delphi_parser.wasm +0 -0
- intentumdiff/wasm/dockerfile_parser.wasm +0 -0
- intentumdiff/wasm/elixir_parser.wasm +0 -0
- intentumdiff/wasm/freebasic_parser.wasm +0 -0
- intentumdiff/wasm/generic_parser.wasm +0 -0
- intentumdiff/wasm/gitignore_parser.wasm +0 -0
- intentumdiff/wasm/go_parser.wasm +0 -0
- intentumdiff/wasm/gomod_parser.wasm +0 -0
- intentumdiff/wasm/graphql_parser.wasm +0 -0
- intentumdiff/wasm/groovy_parser.wasm +0 -0
- intentumdiff/wasm/haskell_parser.wasm +0 -0
- intentumdiff/wasm/html_parser.wasm +0 -0
- intentumdiff/wasm/ini_parser.wasm +0 -0
- intentumdiff/wasm/java_parser.wasm +0 -0
- intentumdiff/wasm/js_ts_parser.wasm +0 -0
- intentumdiff/wasm/json_parser.wasm +0 -0
- intentumdiff/wasm/kotlin_parser.wasm +0 -0
- intentumdiff/wasm/latex_parser.wasm +0 -0
- intentumdiff/wasm/lua_parser.wasm +0 -0
- intentumdiff/wasm/make_parser.wasm +0 -0
- intentumdiff/wasm/markdown_parser.wasm +0 -0
- intentumdiff/wasm/mdx_parser.wasm +0 -0
- intentumdiff/wasm/ocaml_parser.wasm +0 -0
- intentumdiff/wasm/odin_parser.wasm +0 -0
- intentumdiff/wasm/parser_manifest.json +590 -0
- intentumdiff/wasm/perl_parser.wasm +0 -0
- intentumdiff/wasm/php_parser.wasm +0 -0
- intentumdiff/wasm/plsql_parser.wasm +0 -0
- intentumdiff/wasm/po_parser.wasm +0 -0
- intentumdiff/wasm/postscript_parser.wasm +0 -0
- intentumdiff/wasm/powershell_parser.wasm +0 -0
- intentumdiff/wasm/proto_parser.wasm +0 -0
- intentumdiff/wasm/puppet_parser.wasm +0 -0
- intentumdiff/wasm/python_parser.wasm +0 -0
- intentumdiff/wasm/qsharp_parser.wasm +0 -0
- intentumdiff/wasm/r_parser.wasm +0 -0
- intentumdiff/wasm/reasonml_parser.wasm +0 -0
- intentumdiff/wasm/ruby_parser.wasm +0 -0
- intentumdiff/wasm/rust_parser.wasm +0 -0
- intentumdiff/wasm/sas_parser.wasm +0 -0
- intentumdiff/wasm/scala_parser.wasm +0 -0
- intentumdiff/wasm/scss_parser.wasm +0 -0
- intentumdiff/wasm/sql_parser.wasm +0 -0
- intentumdiff/wasm/squirrel_parser.wasm +0 -0
- intentumdiff/wasm/svelte_parser.wasm +0 -0
- intentumdiff/wasm/swift_parser.wasm +0 -0
- intentumdiff/wasm/terraform_parser.wasm +0 -0
- intentumdiff/wasm/toml_parser.wasm +0 -0
- intentumdiff/wasm/tsql_parser.wasm +0 -0
- intentumdiff/wasm/vbnet_parser.wasm +0 -0
- intentumdiff/wasm/vue_parser.wasm +0 -0
- intentumdiff/wasm/wat_parser.wasm +0 -0
- intentumdiff/wasm/xml_parser.wasm +0 -0
- intentumdiff/wasm/yaml_parser.wasm +0 -0
- intentumdiff/wasm/zig_parser.wasm +0 -0
- intentumdiff/watcher.py +259 -0
- intentumdiff_python-0.0.1.dist-info/METADATA +112 -0
- intentumdiff_python-0.0.1.dist-info/RECORD +165 -0
- intentumdiff_python-0.0.1.dist-info/WHEEL +4 -0
- intentumdiff_python-0.0.1.dist-info/entry_points.txt +80 -0
- intentumdiff_python-0.0.1.dist-info/licenses/LICENSE +21 -0
- intentumdiff_python-0.0.1.dist-info/sboms/intentumdiff-rust-core.cyclonedx.json +10968 -0
|
@@ -0,0 +1,1314 @@
|
|
|
1
|
+
"""
|
|
2
|
+
intentumdiff.live_server
|
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
4
|
+
|
|
5
|
+
``LiveServer`` — a persistent socket server for keystroke-level semantic
|
|
6
|
+
diffing.
|
|
7
|
+
|
|
8
|
+
Architecture
|
|
9
|
+
────────────
|
|
10
|
+
* The server keeps a pool of already-initialised ``SemanticDiffer`` instances
|
|
11
|
+
alive between requests, amortising the ~100 ms Wasm initialisation cost.
|
|
12
|
+
* Each connected client sends newline-delimited JSON requests and receives
|
|
13
|
+
newline-delimited JSON responses on the same connection.
|
|
14
|
+
* Per-path **debouncing** (default 150 ms) coalesces bursts of rapid keystrokes
|
|
15
|
+
into a single diff request, matching the behaviour of ``FileWatcher``.
|
|
16
|
+
* A monotonically increasing ``seq`` field lets the server discard stale
|
|
17
|
+
responses when a newer request for the same path has already been queued.
|
|
18
|
+
|
|
19
|
+
Request format
|
|
20
|
+
--------------
|
|
21
|
+
One JSON object per line::
|
|
22
|
+
|
|
23
|
+
{"path": "src/main.py", "content": "...", "seq": 42,
|
|
24
|
+
"ref": "HEAD", "deltas": [...]}
|
|
25
|
+
|
|
26
|
+
``path`` — repository-relative file path (required).
|
|
27
|
+
``content`` — current buffer contents as a string (required).
|
|
28
|
+
``seq`` — monotonically increasing integer; older responses are dropped.
|
|
29
|
+
``ref`` — git ref for the "old" version (optional; default "HEAD").
|
|
30
|
+
``deltas`` — list of ``EditDelta`` dicts for incremental parsing (optional).
|
|
31
|
+
|
|
32
|
+
The repository root is fixed at server startup and cannot be overridden
|
|
33
|
+
per-request.
|
|
34
|
+
|
|
35
|
+
Response format (non-streaming)
|
|
36
|
+
---------------------------------
|
|
37
|
+
::
|
|
38
|
+
|
|
39
|
+
{"seq": 42, "diff": <SemanticDiff JSON>}
|
|
40
|
+
{"seq": 42, "error": "message"}
|
|
41
|
+
|
|
42
|
+
Response format (streaming, ``stream_analysis=True``)
|
|
43
|
+
-----------------------------------------------------
|
|
44
|
+
Multiple lines per request, followed by a ``done`` sentinel::
|
|
45
|
+
|
|
46
|
+
{"seq": 42, "event": <ChangeStreamEvent JSON>}
|
|
47
|
+
...
|
|
48
|
+
{"seq": 42, "done": true}
|
|
49
|
+
|
|
50
|
+
Transport
|
|
51
|
+
---------
|
|
52
|
+
``start_socket()`` opens a Unix-domain socket (``AF_UNIX``) on POSIX and on
|
|
53
|
+
Windows 10 build 17063+ (Python ≥ 3.9). On older Windows it falls back to a
|
|
54
|
+
Windows named pipe (path format ``\\\\.\\pipe\\intentumdiff-live-<random>``), which
|
|
55
|
+
the OS restricts to the creating user via its default ACL — no
|
|
56
|
+
application-level token required.
|
|
57
|
+
The ``start_stdin()`` method provides a simpler pipe-based interface (one
|
|
58
|
+
request → one response, no debouncing) for environments where sockets are
|
|
59
|
+
unavailable.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
from __future__ import annotations
|
|
63
|
+
|
|
64
|
+
from contextlib import suppress
|
|
65
|
+
from dataclasses import dataclass
|
|
66
|
+
import json
|
|
67
|
+
import logging
|
|
68
|
+
import os
|
|
69
|
+
import secrets
|
|
70
|
+
import socket
|
|
71
|
+
import stat
|
|
72
|
+
import sys
|
|
73
|
+
import tempfile
|
|
74
|
+
import threading
|
|
75
|
+
import time
|
|
76
|
+
from pathlib import Path
|
|
77
|
+
from typing import TYPE_CHECKING, Any, Optional
|
|
78
|
+
|
|
79
|
+
if TYPE_CHECKING:
|
|
80
|
+
from intentumdiff.differ import SemanticDiffer
|
|
81
|
+
from rich.console import Console as RichConsole
|
|
82
|
+
|
|
83
|
+
from intentumdiff.core.models import ChangeStreamEvent, EditDelta
|
|
84
|
+
from intentumdiff.sources.live_buffer_source import LiveBufferSource
|
|
85
|
+
|
|
86
|
+
logger = logging.getLogger(__name__)
|
|
87
|
+
|
|
88
|
+
# Maximum bytes buffered per client before the connection is dropped (transport-enforced).
|
|
89
|
+
_MAX_LINE_BYTES = 1_048_576 # 1 MiB
|
|
90
|
+
|
|
91
|
+
# Maximum number of concurrent client connections (transport-enforced).
|
|
92
|
+
_MAX_CLIENTS = 4
|
|
93
|
+
|
|
94
|
+
# NOTE: the content-size and delta-count caps (max_content_bytes / max_deltas) now live in the
|
|
95
|
+
# Rust core (`live_server.rs`, the source of truth) and are advertised via `_limits()`; request
|
|
96
|
+
# validation enforces them there (#100, A2.5).
|
|
97
|
+
|
|
98
|
+
# Editor protocol version emitted by ready/hello/diff responses.
|
|
99
|
+
_PROTOCOL_VERSION = 2
|
|
100
|
+
|
|
101
|
+
# Commit-level review must remain responsive in editors. If a user starts the
|
|
102
|
+
# LiveServer with unlimited active-file parser fuel, review reloads a capped
|
|
103
|
+
# registry so one hard parser case cannot stall the whole Semantic Changes tree.
|
|
104
|
+
_REVIEW_FUEL_WHEN_LIVE_UNLIMITED = 100_000_000
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _wasm_dir() -> str:
|
|
108
|
+
"""The bundled wasm directory (holds the parsers + `parser_manifest.json`) the native diff
|
|
109
|
+
handler reads to resolve a parser for a file. The native live-server binary will bundle its own
|
|
110
|
+
copy; here it is the package's `wasm/` dir."""
|
|
111
|
+
import intentumdiff
|
|
112
|
+
|
|
113
|
+
return str(Path(intentumdiff.__file__).parent / "wasm")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass(frozen=True)
|
|
117
|
+
class _ParsedRequest:
|
|
118
|
+
op: str
|
|
119
|
+
seq: int
|
|
120
|
+
path: str
|
|
121
|
+
content: str
|
|
122
|
+
ref: str
|
|
123
|
+
edit_deltas: list[EditDelta] | None
|
|
124
|
+
stream: bool | None = None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _make_socket_dir() -> str:
|
|
128
|
+
"""Return (and create) a private directory for the server's socket file."""
|
|
129
|
+
runtime_dir = os.environ.get("XDG_RUNTIME_DIR", "")
|
|
130
|
+
if runtime_dir and os.path.isdir(runtime_dir):
|
|
131
|
+
base = runtime_dir
|
|
132
|
+
else:
|
|
133
|
+
base = tempfile.gettempdir()
|
|
134
|
+
|
|
135
|
+
sock_dir = os.path.join(base, f"intentumdiff-{os.getpid()}")
|
|
136
|
+
# 0o700 = OWNER-ONLY rwx — the restrictive choice for the socket dir (the semgrep
|
|
137
|
+
# rule pattern-matches any 0o7xx literal; here it IS the least-permissive mode).
|
|
138
|
+
os.makedirs(sock_dir, mode=0o700, exist_ok=True) # nosemgrep: python.lang.security.audit.insecure-file-permissions.insecure-file-permissions
|
|
139
|
+
# Enforce permissions even if the directory already existed.
|
|
140
|
+
try:
|
|
141
|
+
os.chmod(sock_dir, 0o700) # nosemgrep: python.lang.security.audit.insecure-file-permissions.insecure-file-permissions
|
|
142
|
+
except OSError:
|
|
143
|
+
pass
|
|
144
|
+
return sock_dir
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
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")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _has_unix_socket() -> bool:
|
|
154
|
+
"""Return True when running on POSIX and ``AF_UNIX`` is available.
|
|
155
|
+
|
|
156
|
+
Explicitly excludes Windows: modern Windows builds expose ``AF_UNIX`` in
|
|
157
|
+
the ``socket`` module, but the preferred IPC transport on Windows is a
|
|
158
|
+
named pipe (which allows an explicit security descriptor restricting access
|
|
159
|
+
to the creating user).
|
|
160
|
+
"""
|
|
161
|
+
return sys.platform != "win32" and hasattr(socket, "AF_UNIX")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
# ---------------------------------------------------------------------------
|
|
165
|
+
# Windows named-pipe support (only active on win32 without AF_UNIX)
|
|
166
|
+
# ---------------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
if sys.platform == "win32": # pragma: no cover
|
|
169
|
+
import ctypes
|
|
170
|
+
import ctypes.wintypes as _wt
|
|
171
|
+
|
|
172
|
+
_PIPE_ACCESS_DUPLEX = 0x00000003
|
|
173
|
+
_PIPE_TYPE_BYTE = 0x00000000
|
|
174
|
+
_PIPE_WAIT = 0x00000000
|
|
175
|
+
_PIPE_UNLIMITED_INSTANCES = 255
|
|
176
|
+
_GENERIC_RW = 0xC0000000
|
|
177
|
+
_OPEN_EXISTING = 3
|
|
178
|
+
_FILE_ATTRIBUTE_NORMAL = 0x80
|
|
179
|
+
_ERROR_PIPE_CONNECTED = 535
|
|
180
|
+
_INVALID_HANDLE = ctypes.c_void_p(-1).value
|
|
181
|
+
# PeekNamedPipe is used to check data availability without blocking,
|
|
182
|
+
# avoiding the deadlock that arises from concurrent ReadFile/WriteFile on
|
|
183
|
+
# a synchronous (non-overlapped) named-pipe handle.
|
|
184
|
+
_PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
|
|
185
|
+
_PeekNamedPipe.restype = _wt.BOOL
|
|
186
|
+
_PeekNamedPipe.argtypes = [
|
|
187
|
+
_wt.HANDLE, # hNamedPipe
|
|
188
|
+
ctypes.c_char_p, # lpBuffer (NULL — we only want the byte count)
|
|
189
|
+
_wt.DWORD, # nBufferSize
|
|
190
|
+
ctypes.POINTER(_wt.DWORD), # lpBytesRead
|
|
191
|
+
ctypes.POINTER(_wt.DWORD), # lpTotalBytesAvail
|
|
192
|
+
ctypes.POINTER(_wt.DWORD), # lpBytesLeftThisMessage
|
|
193
|
+
]
|
|
194
|
+
|
|
195
|
+
# --- Security descriptor helpers (DACL for named pipe) ----------------
|
|
196
|
+
_TOKEN_QUERY = 0x0008
|
|
197
|
+
_TOKEN_USER = 1
|
|
198
|
+
|
|
199
|
+
class _SECURITY_ATTRIBUTES(ctypes.Structure): # type: ignore[misc]
|
|
200
|
+
_fields_ = [
|
|
201
|
+
("nLength", _wt.DWORD),
|
|
202
|
+
("lpSecurityDescriptor", ctypes.c_void_p),
|
|
203
|
+
("bInheritHandle", _wt.BOOL),
|
|
204
|
+
]
|
|
205
|
+
|
|
206
|
+
def _get_current_user_sid() -> str:
|
|
207
|
+
"""Return the string SID for the current user (e.g. ``S-1-5-21-...``)."""
|
|
208
|
+
_k32 = ctypes.windll.kernel32
|
|
209
|
+
_adv = ctypes.windll.advapi32
|
|
210
|
+
# GetCurrentProcess returns a pseudo-handle; setting restype to
|
|
211
|
+
# c_void_p prevents sign-extension truncation on 64-bit Windows.
|
|
212
|
+
_k32.GetCurrentProcess.restype = ctypes.c_void_p
|
|
213
|
+
proc = ctypes.c_void_p(_k32.GetCurrentProcess())
|
|
214
|
+
token = _wt.HANDLE(0)
|
|
215
|
+
if not _adv.OpenProcessToken(proc, _TOKEN_QUERY, ctypes.byref(token)):
|
|
216
|
+
raise OSError(
|
|
217
|
+
f"OpenProcessToken failed (error {ctypes.GetLastError()})"
|
|
218
|
+
)
|
|
219
|
+
try:
|
|
220
|
+
# First call: query required buffer size.
|
|
221
|
+
needed = _wt.DWORD(0)
|
|
222
|
+
_adv.GetTokenInformation(
|
|
223
|
+
token, _TOKEN_USER, None, 0, ctypes.byref(needed)
|
|
224
|
+
)
|
|
225
|
+
buf = ctypes.create_string_buffer(needed.value)
|
|
226
|
+
if not _adv.GetTokenInformation(
|
|
227
|
+
token, _TOKEN_USER, buf, needed, ctypes.byref(needed)
|
|
228
|
+
):
|
|
229
|
+
raise OSError(
|
|
230
|
+
f"GetTokenInformation failed (error {ctypes.GetLastError()})"
|
|
231
|
+
)
|
|
232
|
+
# TOKEN_USER.User.Sid is a SID pointer at offset 0 of the struct.
|
|
233
|
+
sid_addr = ctypes.cast(buf, ctypes.POINTER(ctypes.c_void_p))[0]
|
|
234
|
+
# ConvertSidToStringSidW allocates the output string via
|
|
235
|
+
# LocalAlloc; we must call LocalFree to release it.
|
|
236
|
+
str_buf = ctypes.c_void_p()
|
|
237
|
+
if not _adv.ConvertSidToStringSidW(
|
|
238
|
+
ctypes.c_void_p(sid_addr), ctypes.byref(str_buf)
|
|
239
|
+
):
|
|
240
|
+
raise OSError(
|
|
241
|
+
"ConvertSidToStringSidW failed "
|
|
242
|
+
f"(error {ctypes.GetLastError()})"
|
|
243
|
+
)
|
|
244
|
+
try:
|
|
245
|
+
return ctypes.c_wchar_p(str_buf.value).value # type: ignore[return-value]
|
|
246
|
+
finally:
|
|
247
|
+
_k32.LocalFree(str_buf)
|
|
248
|
+
finally:
|
|
249
|
+
_k32.CloseHandle(token)
|
|
250
|
+
|
|
251
|
+
# Build the pipe SECURITY_ATTRIBUTES once at import time using SDDL
|
|
252
|
+
# D:P(A;;GA;;;{user_sid})(A;;GA;;;SY) — a Protected DACL granting
|
|
253
|
+
# Generic All to the current user and SYSTEM only. The P flag blocks
|
|
254
|
+
# DACL inheritance. Keeping the security descriptor alive at module
|
|
255
|
+
# scope eliminates per-call overhead in the accept loop, avoiding the
|
|
256
|
+
# timing race between ConnectNamedPipe and the stop() dummy connection.
|
|
257
|
+
_pipe_sa: "Optional[_SECURITY_ATTRIBUTES]" = None
|
|
258
|
+
_pipe_sd: "Optional[ctypes.c_void_p]" = None # kept alive; freed at exit
|
|
259
|
+
try:
|
|
260
|
+
_uid = _get_current_user_sid()
|
|
261
|
+
_sddl = f"D:P(A;;GA;;;{_uid})(A;;GA;;;SY)"
|
|
262
|
+
_sd = ctypes.c_void_p()
|
|
263
|
+
if ctypes.windll.advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
|
264
|
+
_sddl, 1, ctypes.byref(_sd), None
|
|
265
|
+
):
|
|
266
|
+
_pipe_sa = _SECURITY_ATTRIBUTES()
|
|
267
|
+
_pipe_sa.nLength = ctypes.sizeof(_SECURITY_ATTRIBUTES)
|
|
268
|
+
_pipe_sa.lpSecurityDescriptor = _sd
|
|
269
|
+
_pipe_sa.bInheritHandle = False
|
|
270
|
+
_pipe_sd = _sd
|
|
271
|
+
else:
|
|
272
|
+
logger.warning(
|
|
273
|
+
"LiveServer: ConvertStringSecurityDescriptorToSecurityDescriptorW "
|
|
274
|
+
"failed (error %d); named pipes will use the default DACL",
|
|
275
|
+
ctypes.GetLastError(),
|
|
276
|
+
)
|
|
277
|
+
except OSError as _dacl_exc:
|
|
278
|
+
logger.warning(
|
|
279
|
+
"LiveServer: could not build pipe security descriptor (%s); "
|
|
280
|
+
"named pipes will use the default DACL",
|
|
281
|
+
_dacl_exc,
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
def _create_named_pipe_handle(name: str) -> "ctypes.c_void_p":
|
|
285
|
+
"""Create a new named-pipe server instance and return its handle.
|
|
286
|
+
|
|
287
|
+
Uses the module-level ``_pipe_sa`` ``SECURITY_ATTRIBUTES`` struct
|
|
288
|
+
(built once at import time) with SDDL
|
|
289
|
+
``D:P(A;;GA;;;{user_sid})(A;;GA;;;SY)`` so the pipe ACL grants
|
|
290
|
+
access only to the creating user and SYSTEM, regardless of the
|
|
291
|
+
process token's default DACL. Falls back silently to the default
|
|
292
|
+
DACL when the module-level struct could not be built.
|
|
293
|
+
"""
|
|
294
|
+
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,
|
|
302
|
+
ctypes.byref(_pipe_sa) if _pipe_sa is not None else None, # type: ignore[name-defined]
|
|
303
|
+
)
|
|
304
|
+
if handle == _INVALID_HANDLE:
|
|
305
|
+
raise OSError(
|
|
306
|
+
f"CreateNamedPipeW failed (error {ctypes.GetLastError()})"
|
|
307
|
+
)
|
|
308
|
+
return handle
|
|
309
|
+
|
|
310
|
+
def _open_pipe_client(name: str) -> None:
|
|
311
|
+
"""Open a short-lived client connection to unblock ConnectNamedPipe."""
|
|
312
|
+
ctypes.windll.kernel32.WaitNamedPipeW(name, 100)
|
|
313
|
+
h = ctypes.windll.kernel32.CreateFileW(
|
|
314
|
+
name, _GENERIC_RW, 0, None, _OPEN_EXISTING, _FILE_ATTRIBUTE_NORMAL, None
|
|
315
|
+
)
|
|
316
|
+
if h != _INVALID_HANDLE:
|
|
317
|
+
ctypes.windll.kernel32.CloseHandle(h)
|
|
318
|
+
|
|
319
|
+
class _NamedPipeConn:
|
|
320
|
+
"""Socket-compatible wrapper around a Windows named-pipe handle.
|
|
321
|
+
|
|
322
|
+
Provides the ``recv`` / ``sendall`` / ``close`` / context-manager
|
|
323
|
+
interface that ``_handle_client`` and ``_write_line_bytes`` expect.
|
|
324
|
+
|
|
325
|
+
**Why PeekNamedPipe instead of blocking ReadFile?**
|
|
326
|
+
Windows serializes *all* I/O on a synchronous (non-overlapped) named-
|
|
327
|
+
pipe handle — reads *and* writes. If ``_handle_client`` blocks on
|
|
328
|
+
``ReadFile`` while waiting for the next request, the timer thread
|
|
329
|
+
cannot call ``WriteFile`` to send the current response, creating a
|
|
330
|
+
deadlock. ``PeekNamedPipe`` is non-blocking and does not hold the
|
|
331
|
+
handle's I/O queue, so ``WriteFile`` from the timer thread can proceed
|
|
332
|
+
while this thread is sleeping between peeks.
|
|
333
|
+
"""
|
|
334
|
+
|
|
335
|
+
_POLL_INTERVAL = 0.001 # 1 ms — imperceptible for human-speed editing
|
|
336
|
+
|
|
337
|
+
def __init__(
|
|
338
|
+
self,
|
|
339
|
+
handle: "ctypes.c_void_p",
|
|
340
|
+
stop_event: threading.Event,
|
|
341
|
+
) -> None:
|
|
342
|
+
self._handle = handle
|
|
343
|
+
self._stop_event = stop_event
|
|
344
|
+
self._closed = False
|
|
345
|
+
|
|
346
|
+
def settimeout(self, timeout: float) -> None: # noqa: ARG002
|
|
347
|
+
"""No-op: termination is driven by stop_event, not a socket timeout."""
|
|
348
|
+
|
|
349
|
+
def recv(self, size: int) -> bytes:
|
|
350
|
+
"""Return up to *size* bytes, polling until data arrives or the
|
|
351
|
+
server stop-event is set."""
|
|
352
|
+
avail = _wt.DWORD(0)
|
|
353
|
+
while not self._stop_event.is_set():
|
|
354
|
+
ok = _PeekNamedPipe(
|
|
355
|
+
self._handle, None, 0, None, ctypes.byref(avail), None
|
|
356
|
+
)
|
|
357
|
+
if not ok:
|
|
358
|
+
return b"" # pipe broken
|
|
359
|
+
if avail.value > 0:
|
|
360
|
+
to_read = min(size, avail.value)
|
|
361
|
+
buf = ctypes.create_string_buffer(to_read)
|
|
362
|
+
n_read = _wt.DWORD(0)
|
|
363
|
+
ok2 = ctypes.windll.kernel32.ReadFile(
|
|
364
|
+
self._handle, buf, to_read, ctypes.byref(n_read), None
|
|
365
|
+
)
|
|
366
|
+
return buf.raw[: n_read.value] if ok2 else b""
|
|
367
|
+
time.sleep(self._POLL_INTERVAL)
|
|
368
|
+
return b"" # stop requested
|
|
369
|
+
|
|
370
|
+
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
|
+
)
|
|
375
|
+
|
|
376
|
+
def close(self) -> None:
|
|
377
|
+
if not self._closed:
|
|
378
|
+
self._closed = True
|
|
379
|
+
ctypes.windll.kernel32.DisconnectNamedPipe(self._handle)
|
|
380
|
+
ctypes.windll.kernel32.CloseHandle(self._handle)
|
|
381
|
+
|
|
382
|
+
def __enter__(self) -> "_NamedPipeConn":
|
|
383
|
+
return self
|
|
384
|
+
|
|
385
|
+
def __exit__(self, *_: object) -> None:
|
|
386
|
+
self.close()
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
class _ReviewCancelled(Exception):
|
|
390
|
+
"""Raised internally when a streaming review is superseded by a newer request."""
|
|
391
|
+
|
|
392
|
+
def __init__(self, seq: int) -> None:
|
|
393
|
+
super().__init__(f"streaming review seq={seq} superseded")
|
|
394
|
+
self.seq = seq
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
class LiveServer:
|
|
398
|
+
"""Persistent socket server for keystroke-level semantic diffing.
|
|
399
|
+
|
|
400
|
+
Parameters
|
|
401
|
+
----------
|
|
402
|
+
differ:
|
|
403
|
+
A configured :class:`~intentumdiff.differ.SemanticDiffer` instance.
|
|
404
|
+
repo_path:
|
|
405
|
+
Repository root to use for all diff requests. Clients are **not**
|
|
406
|
+
permitted to override this via the request payload — doing so would
|
|
407
|
+
allow path traversal into arbitrary directories.
|
|
408
|
+
ref:
|
|
409
|
+
Git ref to compare live buffers against (default: ``"HEAD"``).
|
|
410
|
+
debounce:
|
|
411
|
+
Seconds to wait after the last request for a given path before
|
|
412
|
+
running the diff. Default 0.15 (150 ms).
|
|
413
|
+
console:
|
|
414
|
+
Optional :class:`rich.console.Console` for status messages.
|
|
415
|
+
stream_analysis:
|
|
416
|
+
When ``True``, responses are sent as a sequence of
|
|
417
|
+
``ChangeStreamEvent`` objects followed by a ``done`` sentinel.
|
|
418
|
+
When ``False`` (default), a single ``SemanticDiff`` JSON object is
|
|
419
|
+
sent per request.
|
|
420
|
+
"""
|
|
421
|
+
|
|
422
|
+
def __init__(
|
|
423
|
+
self,
|
|
424
|
+
differ: "SemanticDiffer",
|
|
425
|
+
*,
|
|
426
|
+
repo_path: "str | Path",
|
|
427
|
+
ref: str = "HEAD",
|
|
428
|
+
debounce: float = 0.15,
|
|
429
|
+
console: "RichConsole | None" = None,
|
|
430
|
+
stream_analysis: bool = False,
|
|
431
|
+
) -> None:
|
|
432
|
+
self._differ = differ
|
|
433
|
+
self._repo_path = str(repo_path)
|
|
434
|
+
self._ref = ref
|
|
435
|
+
self._debounce = debounce
|
|
436
|
+
self._console = console
|
|
437
|
+
self._stream_analysis = stream_analysis
|
|
438
|
+
|
|
439
|
+
# Random token — used in socket path so guessing the socket requires
|
|
440
|
+
# knowledge of the token.
|
|
441
|
+
self._token: str = secrets.token_hex(32)
|
|
442
|
+
|
|
443
|
+
self._lock = threading.Lock()
|
|
444
|
+
# Debounce timers: path → threading.Timer
|
|
445
|
+
self._timers: dict[str, threading.Timer] = {}
|
|
446
|
+
self._timer_requests: dict[str, _ParsedRequest] = {}
|
|
447
|
+
# Latest seen seq per path (for late-response discarding)
|
|
448
|
+
self._latest_seq: dict[str, int] = {}
|
|
449
|
+
self._latest_review_seq: int = 0
|
|
450
|
+
# Active client connection count
|
|
451
|
+
self._client_count: int = 0
|
|
452
|
+
|
|
453
|
+
self._stop_event = threading.Event()
|
|
454
|
+
self._server_thread: threading.Thread | None = None
|
|
455
|
+
self._server_socket: socket.socket | None = None
|
|
456
|
+
# Set only when the Windows named-pipe fallback is active.
|
|
457
|
+
self._pipe_name: str | None = None
|
|
458
|
+
|
|
459
|
+
# ------------------------------------------------------------------
|
|
460
|
+
# Public API
|
|
461
|
+
# ------------------------------------------------------------------
|
|
462
|
+
# Public API
|
|
463
|
+
# ------------------------------------------------------------------
|
|
464
|
+
|
|
465
|
+
def ready_message(
|
|
466
|
+
self,
|
|
467
|
+
*,
|
|
468
|
+
transport: str = "stdio",
|
|
469
|
+
address: str | None = None,
|
|
470
|
+
) -> dict[str, Any]:
|
|
471
|
+
"""Return the protocol-v2 startup/capability payload."""
|
|
472
|
+
|
|
473
|
+
payload: dict[str, Any] = {
|
|
474
|
+
"op": "ready",
|
|
475
|
+
"ok": True,
|
|
476
|
+
"protocol_version": _PROTOCOL_VERSION,
|
|
477
|
+
"repo_path": self._repo_path,
|
|
478
|
+
"ref": self._ref,
|
|
479
|
+
"transport": transport,
|
|
480
|
+
"limits": self._limits(),
|
|
481
|
+
"capabilities": self._capabilities(),
|
|
482
|
+
}
|
|
483
|
+
if address is not None:
|
|
484
|
+
payload["address"] = address
|
|
485
|
+
return payload
|
|
486
|
+
|
|
487
|
+
def start_socket(self, socket_path: str | None = None) -> str:
|
|
488
|
+
"""Start the background socket listener.
|
|
489
|
+
|
|
490
|
+
Returns the socket address string: a Unix-socket path on POSIX /
|
|
491
|
+
modern Windows, or a ``\\\\.\\pipe\\...`` name on older Windows.
|
|
492
|
+
"""
|
|
493
|
+
if _has_unix_socket():
|
|
494
|
+
path = socket_path or _make_socket_path(os.getpid(), self._token)
|
|
495
|
+
# Remove stale socket file if it exists.
|
|
496
|
+
try:
|
|
497
|
+
os.unlink(path)
|
|
498
|
+
except FileNotFoundError:
|
|
499
|
+
pass
|
|
500
|
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
501
|
+
sock.bind(path)
|
|
502
|
+
# Restrict access to the owning user.
|
|
503
|
+
try:
|
|
504
|
+
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
|
|
505
|
+
except OSError:
|
|
506
|
+
pass
|
|
507
|
+
addr: str = path
|
|
508
|
+
else:
|
|
509
|
+
# Older Windows (no AF_UNIX): use a named pipe. The OS default
|
|
510
|
+
# ACL restricts access to the creating user — no token needed.
|
|
511
|
+
pipe_name = r"\\.\pipe\intentumdiff-live-" + secrets.token_hex(8)
|
|
512
|
+
self._pipe_name = pipe_name
|
|
513
|
+
addr = pipe_name
|
|
514
|
+
|
|
515
|
+
self._server_thread = threading.Thread(
|
|
516
|
+
target=self._named_pipe_accept_loop,
|
|
517
|
+
name="LiveServer-accept",
|
|
518
|
+
daemon=True,
|
|
519
|
+
)
|
|
520
|
+
self._server_thread.start()
|
|
521
|
+
|
|
522
|
+
if self._console is not None:
|
|
523
|
+
self._console.print(f"[dim]LiveServer listening on {addr}[/dim]")
|
|
524
|
+
|
|
525
|
+
return addr
|
|
526
|
+
|
|
527
|
+
sock.listen(4) # small backlog — only local editor processes connect
|
|
528
|
+
sock.settimeout(1.0) # Allow periodic stop-event checks
|
|
529
|
+
self._server_socket = sock
|
|
530
|
+
|
|
531
|
+
self._server_thread = threading.Thread(
|
|
532
|
+
target=self._accept_loop,
|
|
533
|
+
name="LiveServer-accept",
|
|
534
|
+
daemon=True,
|
|
535
|
+
)
|
|
536
|
+
self._server_thread.start()
|
|
537
|
+
|
|
538
|
+
if self._console is not None:
|
|
539
|
+
self._console.print(f"[dim]LiveServer listening on {addr}[/dim]")
|
|
540
|
+
|
|
541
|
+
return addr
|
|
542
|
+
|
|
543
|
+
def start_stdin(self) -> None:
|
|
544
|
+
"""Read requests from stdin and write responses to stdout (blocking).
|
|
545
|
+
|
|
546
|
+
Each line of stdin is treated as a JSON request object. Responses are
|
|
547
|
+
written as a single JSON line (or multiple lines when streaming).
|
|
548
|
+
No debouncing is applied — each request is processed immediately.
|
|
549
|
+
"""
|
|
550
|
+
_write_line(sys.stdout, self.ready_message(transport="stdio"))
|
|
551
|
+
for line in sys.stdin:
|
|
552
|
+
line = line.strip()
|
|
553
|
+
if not line:
|
|
554
|
+
continue
|
|
555
|
+
try:
|
|
556
|
+
request = json.loads(line)
|
|
557
|
+
except json.JSONDecodeError as exc:
|
|
558
|
+
_write_line(
|
|
559
|
+
sys.stdout,
|
|
560
|
+
self._error_response(
|
|
561
|
+
0,
|
|
562
|
+
"invalid_json",
|
|
563
|
+
f"JSON parse error: {exc}",
|
|
564
|
+
),
|
|
565
|
+
)
|
|
566
|
+
continue
|
|
567
|
+
|
|
568
|
+
def _write(obj: dict[str, Any]) -> None:
|
|
569
|
+
_write_line(sys.stdout, obj)
|
|
570
|
+
|
|
571
|
+
self._process_request(request, _write)
|
|
572
|
+
|
|
573
|
+
def stop(self) -> None:
|
|
574
|
+
"""Signal the server to stop and wait for the background thread."""
|
|
575
|
+
self._stop_event.set()
|
|
576
|
+
if self._server_socket is not None:
|
|
577
|
+
try:
|
|
578
|
+
self._server_socket.close()
|
|
579
|
+
except OSError:
|
|
580
|
+
pass
|
|
581
|
+
if self._pipe_name is not None and self._server_thread is not None:
|
|
582
|
+
# Unblock the blocking ConnectNamedPipe in the accept loop by opening
|
|
583
|
+
# dummy client connections UNTIL the thread exits. A fixed retry budget
|
|
584
|
+
# raced under load (#73 flake): when the accept thread was starved
|
|
585
|
+
# between CloseHandle and its next CreateNamedPipeW, every dummy
|
|
586
|
+
# connect failed instantly (no pipe instance existed yet) and the
|
|
587
|
+
# thread later blocked forever. Nudging against thread liveness is
|
|
588
|
+
# deterministic — the first connect after the thread blocks wins.
|
|
589
|
+
deadline = time.monotonic() + 10.0
|
|
590
|
+
while self._server_thread.is_alive() and time.monotonic() < deadline:
|
|
591
|
+
with suppress(Exception):
|
|
592
|
+
_open_pipe_client(self._pipe_name) # type: ignore[name-defined]
|
|
593
|
+
self._server_thread.join(timeout=0.05)
|
|
594
|
+
with self._lock:
|
|
595
|
+
for timer in list(self._timers.values()):
|
|
596
|
+
timer.cancel()
|
|
597
|
+
self._timers.clear()
|
|
598
|
+
self._timer_requests.clear()
|
|
599
|
+
if self._server_thread is not None:
|
|
600
|
+
self._server_thread.join(timeout=3.0)
|
|
601
|
+
|
|
602
|
+
# ------------------------------------------------------------------
|
|
603
|
+
# Internal: accept loops (socket and named pipe)
|
|
604
|
+
# ------------------------------------------------------------------
|
|
605
|
+
|
|
606
|
+
def _named_pipe_accept_loop(self) -> None: # pragma: no cover
|
|
607
|
+
"""Background thread: accept connections on the Windows named pipe."""
|
|
608
|
+
while not self._stop_event.is_set():
|
|
609
|
+
try:
|
|
610
|
+
handle = _create_named_pipe_handle(self._pipe_name) # type: ignore[arg-type,name-defined]
|
|
611
|
+
except OSError as exc:
|
|
612
|
+
logger.error("LiveServer: cannot create named pipe: %s", exc)
|
|
613
|
+
break
|
|
614
|
+
|
|
615
|
+
connected = ctypes.windll.kernel32.ConnectNamedPipe(handle, None) # type: ignore[name-defined]
|
|
616
|
+
err = ctypes.GetLastError() # type: ignore[name-defined]
|
|
617
|
+
|
|
618
|
+
# ConnectNamedPipe returns 0 on error; ERROR_PIPE_CONNECTED (535)
|
|
619
|
+
# means a client connected between CreateNamedPipeW and
|
|
620
|
+
# ConnectNamedPipe — still valid.
|
|
621
|
+
pipe_ok = connected != 0 or err in (0, _ERROR_PIPE_CONNECTED) # type: ignore[name-defined]
|
|
622
|
+
|
|
623
|
+
if not pipe_ok:
|
|
624
|
+
ctypes.windll.kernel32.CloseHandle(handle) # type: ignore[name-defined]
|
|
625
|
+
if self._stop_event.is_set():
|
|
626
|
+
break
|
|
627
|
+
continue
|
|
628
|
+
|
|
629
|
+
if self._stop_event.is_set():
|
|
630
|
+
ctypes.windll.kernel32.CloseHandle(handle) # type: ignore[name-defined]
|
|
631
|
+
break
|
|
632
|
+
|
|
633
|
+
with self._lock:
|
|
634
|
+
if self._client_count >= _MAX_CLIENTS:
|
|
635
|
+
logger.warning(
|
|
636
|
+
"LiveServer: max concurrent clients (%d) reached; "
|
|
637
|
+
"rejecting new connection.",
|
|
638
|
+
_MAX_CLIENTS,
|
|
639
|
+
)
|
|
640
|
+
try:
|
|
641
|
+
with _NamedPipeConn(handle, self._stop_event) as tmp: # type: ignore[name-defined]
|
|
642
|
+
_write_line_bytes(
|
|
643
|
+
tmp,
|
|
644
|
+
self._error_response(
|
|
645
|
+
0,
|
|
646
|
+
"too_many_clients",
|
|
647
|
+
"too many concurrent clients",
|
|
648
|
+
),
|
|
649
|
+
)
|
|
650
|
+
except OSError:
|
|
651
|
+
pass
|
|
652
|
+
continue
|
|
653
|
+
self._client_count += 1
|
|
654
|
+
|
|
655
|
+
client_thread = threading.Thread(
|
|
656
|
+
target=self._handle_client,
|
|
657
|
+
args=(_NamedPipeConn(handle, self._stop_event),), # type: ignore[name-defined]
|
|
658
|
+
name="LiveServer-client",
|
|
659
|
+
daemon=True,
|
|
660
|
+
)
|
|
661
|
+
client_thread.start()
|
|
662
|
+
|
|
663
|
+
def _accept_loop(self) -> None:
|
|
664
|
+
"""Background thread: accept connections and spawn per-client threads."""
|
|
665
|
+
if self._server_socket is None:
|
|
666
|
+
logger.debug("LiveServer accept loop started without a server socket")
|
|
667
|
+
return
|
|
668
|
+
while not self._stop_event.is_set():
|
|
669
|
+
try:
|
|
670
|
+
conn, _ = self._server_socket.accept()
|
|
671
|
+
except socket.timeout:
|
|
672
|
+
continue
|
|
673
|
+
except OSError:
|
|
674
|
+
break
|
|
675
|
+
|
|
676
|
+
with self._lock:
|
|
677
|
+
if self._client_count >= _MAX_CLIENTS:
|
|
678
|
+
# Too many concurrent clients — reject immediately.
|
|
679
|
+
logger.warning(
|
|
680
|
+
"LiveServer: max concurrent clients (%d) reached; "
|
|
681
|
+
"rejecting new connection.",
|
|
682
|
+
_MAX_CLIENTS,
|
|
683
|
+
)
|
|
684
|
+
try:
|
|
685
|
+
_write_line_bytes(
|
|
686
|
+
conn,
|
|
687
|
+
self._error_response(
|
|
688
|
+
0,
|
|
689
|
+
"too_many_clients",
|
|
690
|
+
"too many concurrent clients",
|
|
691
|
+
),
|
|
692
|
+
)
|
|
693
|
+
conn.close()
|
|
694
|
+
except OSError:
|
|
695
|
+
pass
|
|
696
|
+
continue
|
|
697
|
+
self._client_count += 1
|
|
698
|
+
|
|
699
|
+
client_thread = threading.Thread(
|
|
700
|
+
target=self._handle_client,
|
|
701
|
+
args=(conn,),
|
|
702
|
+
name="LiveServer-client",
|
|
703
|
+
daemon=True,
|
|
704
|
+
)
|
|
705
|
+
client_thread.start()
|
|
706
|
+
|
|
707
|
+
def _handle_client(self, conn: socket.socket) -> None:
|
|
708
|
+
"""Serve a single connected client until it disconnects."""
|
|
709
|
+
buf = b""
|
|
710
|
+
try:
|
|
711
|
+
with conn:
|
|
712
|
+
conn.settimeout(30.0) # per-read timeout to release idle connections
|
|
713
|
+
while not self._stop_event.is_set():
|
|
714
|
+
try:
|
|
715
|
+
chunk = conn.recv(65536)
|
|
716
|
+
except socket.timeout:
|
|
717
|
+
# No activity for 30 s — close to free resources.
|
|
718
|
+
logger.debug("LiveServer: client timed out (idle)")
|
|
719
|
+
break
|
|
720
|
+
if not chunk:
|
|
721
|
+
break
|
|
722
|
+
buf += chunk
|
|
723
|
+
# Guard against runaway clients sending gigantic payloads.
|
|
724
|
+
if len(buf) > _MAX_LINE_BYTES and b"\n" not in buf:
|
|
725
|
+
logger.warning(
|
|
726
|
+
"LiveServer: client sent >%d bytes without newline; dropping.",
|
|
727
|
+
_MAX_LINE_BYTES,
|
|
728
|
+
)
|
|
729
|
+
_write_line_bytes(conn, {"error": "request too large"})
|
|
730
|
+
break
|
|
731
|
+
while b"\n" in buf:
|
|
732
|
+
line_bytes, buf = buf.split(b"\n", 1)
|
|
733
|
+
if len(line_bytes) > _MAX_LINE_BYTES:
|
|
734
|
+
_write_line_bytes(conn, {"error": "request line too large"})
|
|
735
|
+
buf = b""
|
|
736
|
+
break
|
|
737
|
+
line = line_bytes.decode("utf-8", errors="replace").strip()
|
|
738
|
+
if not line:
|
|
739
|
+
continue
|
|
740
|
+
try:
|
|
741
|
+
request = json.loads(line)
|
|
742
|
+
except json.JSONDecodeError as exc:
|
|
743
|
+
_write_line_bytes(
|
|
744
|
+
conn,
|
|
745
|
+
self._error_response(
|
|
746
|
+
0,
|
|
747
|
+
"invalid_json",
|
|
748
|
+
f"JSON parse error: {exc}",
|
|
749
|
+
),
|
|
750
|
+
)
|
|
751
|
+
continue
|
|
752
|
+
|
|
753
|
+
def _send(obj: dict[str, Any], _conn: socket.socket = conn) -> None:
|
|
754
|
+
_write_line_bytes(_conn, obj)
|
|
755
|
+
|
|
756
|
+
self._schedule_request(request, _send)
|
|
757
|
+
except OSError as exc:
|
|
758
|
+
logger.debug("Client connection error: %s", exc)
|
|
759
|
+
finally:
|
|
760
|
+
with self._lock:
|
|
761
|
+
self._client_count = max(0, self._client_count - 1)
|
|
762
|
+
|
|
763
|
+
# ------------------------------------------------------------------
|
|
764
|
+
# Internal: debounce + dispatch
|
|
765
|
+
# ------------------------------------------------------------------
|
|
766
|
+
|
|
767
|
+
def _schedule_request(
|
|
768
|
+
self,
|
|
769
|
+
request: dict[str, Any],
|
|
770
|
+
send_fn: "Any", # Callable[[dict], None]
|
|
771
|
+
) -> None:
|
|
772
|
+
"""Debounce incoming requests per path and schedule a diff run."""
|
|
773
|
+
if not isinstance(request, dict):
|
|
774
|
+
send_fn(self._error_response(0, "invalid_request", "request must be an object"))
|
|
775
|
+
return
|
|
776
|
+
if self._handle_control_request(request, send_fn):
|
|
777
|
+
return
|
|
778
|
+
parsed, error = self._parse_diff_request(request)
|
|
779
|
+
if error is not None:
|
|
780
|
+
send_fn(error)
|
|
781
|
+
return
|
|
782
|
+
if parsed is None:
|
|
783
|
+
send_fn(
|
|
784
|
+
self._error_response(
|
|
785
|
+
0,
|
|
786
|
+
"invalid_request",
|
|
787
|
+
"request parser returned no diff request",
|
|
788
|
+
op="diff",
|
|
789
|
+
)
|
|
790
|
+
)
|
|
791
|
+
return
|
|
792
|
+
|
|
793
|
+
with self._lock:
|
|
794
|
+
# Track the latest seq for this path so older responses can be dropped.
|
|
795
|
+
self._latest_seq[parsed.path] = max(
|
|
796
|
+
self._latest_seq.get(parsed.path, 0),
|
|
797
|
+
parsed.seq,
|
|
798
|
+
)
|
|
799
|
+
|
|
800
|
+
# Cancel any pending timer for this path.
|
|
801
|
+
existing = self._timers.pop(parsed.path, None)
|
|
802
|
+
if existing is not None:
|
|
803
|
+
existing.cancel()
|
|
804
|
+
self._timer_requests.pop(parsed.path, None)
|
|
805
|
+
|
|
806
|
+
timer = threading.Timer(
|
|
807
|
+
self._debounce,
|
|
808
|
+
self._run_diff,
|
|
809
|
+
args=(parsed, send_fn),
|
|
810
|
+
)
|
|
811
|
+
self._timers[parsed.path] = timer
|
|
812
|
+
self._timer_requests[parsed.path] = parsed
|
|
813
|
+
timer.start()
|
|
814
|
+
|
|
815
|
+
def _run_diff(
|
|
816
|
+
self,
|
|
817
|
+
request: _ParsedRequest,
|
|
818
|
+
send_fn: "Any",
|
|
819
|
+
) -> None:
|
|
820
|
+
"""Execute the diff for a debounced request and send the response."""
|
|
821
|
+
with self._lock:
|
|
822
|
+
self._timers.pop(request.path, None)
|
|
823
|
+
self._timer_requests.pop(request.path, None)
|
|
824
|
+
latest_seq = self._latest_seq.get(request.path, 0)
|
|
825
|
+
|
|
826
|
+
if request.seq < latest_seq:
|
|
827
|
+
logger.debug(
|
|
828
|
+
"Dropping stale seq=%d for %r (latest=%d)",
|
|
829
|
+
request.seq,
|
|
830
|
+
request.path,
|
|
831
|
+
latest_seq,
|
|
832
|
+
)
|
|
833
|
+
return
|
|
834
|
+
|
|
835
|
+
source = LiveBufferSource(
|
|
836
|
+
repo_path=self._repo_path,
|
|
837
|
+
file_path=request.path,
|
|
838
|
+
live_content=request.content,
|
|
839
|
+
ref=request.ref,
|
|
840
|
+
edit_deltas=request.edit_deltas,
|
|
841
|
+
)
|
|
842
|
+
|
|
843
|
+
self._process_request_with_source(source, request, send_fn)
|
|
844
|
+
|
|
845
|
+
def _process_request_legacy(
|
|
846
|
+
self,
|
|
847
|
+
request: dict[str, Any],
|
|
848
|
+
send_fn: "Any",
|
|
849
|
+
) -> None:
|
|
850
|
+
"""Process a request immediately (no debounce — used by start_stdin)."""
|
|
851
|
+
raise NotImplementedError
|
|
852
|
+
|
|
853
|
+
def _process_request_with_source_legacy(
|
|
854
|
+
self,
|
|
855
|
+
source: LiveBufferSource,
|
|
856
|
+
seq: int,
|
|
857
|
+
send_fn: "Any",
|
|
858
|
+
) -> None:
|
|
859
|
+
"""Run the differ against *source* and send the response via *send_fn*."""
|
|
860
|
+
raise NotImplementedError
|
|
861
|
+
|
|
862
|
+
def _process_request(
|
|
863
|
+
self,
|
|
864
|
+
request: dict[str, Any],
|
|
865
|
+
send_fn: "Any",
|
|
866
|
+
) -> None:
|
|
867
|
+
"""Process a request immediately using the protocol-v2 parser."""
|
|
868
|
+
if not isinstance(request, dict):
|
|
869
|
+
send_fn(self._error_response(0, "invalid_request", "request must be an object"))
|
|
870
|
+
return
|
|
871
|
+
if self._handle_control_request(request, send_fn):
|
|
872
|
+
return
|
|
873
|
+
parsed, error = self._parse_diff_request(request)
|
|
874
|
+
if error is not None:
|
|
875
|
+
send_fn(error)
|
|
876
|
+
return
|
|
877
|
+
if parsed is None:
|
|
878
|
+
send_fn(
|
|
879
|
+
self._error_response(
|
|
880
|
+
0,
|
|
881
|
+
"invalid_request",
|
|
882
|
+
"request parser returned no diff request",
|
|
883
|
+
op="diff",
|
|
884
|
+
)
|
|
885
|
+
)
|
|
886
|
+
return
|
|
887
|
+
|
|
888
|
+
source = LiveBufferSource(
|
|
889
|
+
repo_path=self._repo_path,
|
|
890
|
+
file_path=parsed.path,
|
|
891
|
+
live_content=parsed.content,
|
|
892
|
+
ref=parsed.ref,
|
|
893
|
+
edit_deltas=parsed.edit_deltas,
|
|
894
|
+
)
|
|
895
|
+
self._process_request_with_source(source, parsed, send_fn)
|
|
896
|
+
|
|
897
|
+
def _process_request_with_source(
|
|
898
|
+
self,
|
|
899
|
+
source: LiveBufferSource,
|
|
900
|
+
request: _ParsedRequest,
|
|
901
|
+
send_fn: "Any",
|
|
902
|
+
) -> None:
|
|
903
|
+
"""Run the differ against *source* and send a protocol-v2 response."""
|
|
904
|
+
start = time.perf_counter()
|
|
905
|
+
use_stream = self._stream_analysis if request.stream is None else request.stream
|
|
906
|
+
try:
|
|
907
|
+
if use_stream:
|
|
908
|
+
for event in self._differ.diff_stream_progressive(source):
|
|
909
|
+
if self._is_stale(request):
|
|
910
|
+
return
|
|
911
|
+
send_fn({
|
|
912
|
+
"op": "diff",
|
|
913
|
+
"seq": request.seq,
|
|
914
|
+
"ok": True,
|
|
915
|
+
"event": json.loads(event.model_dump_json()),
|
|
916
|
+
})
|
|
917
|
+
if self._is_stale(request):
|
|
918
|
+
return
|
|
919
|
+
send_fn({"op": "diff", "seq": request.seq, "ok": True, "done": True})
|
|
920
|
+
else:
|
|
921
|
+
diff = self._compute_diff(source, request)
|
|
922
|
+
if self._is_stale(request):
|
|
923
|
+
return
|
|
924
|
+
duration_ms = round((time.perf_counter() - start) * 1000, 3)
|
|
925
|
+
send_fn({
|
|
926
|
+
"op": "diff",
|
|
927
|
+
"seq": request.seq,
|
|
928
|
+
"ok": True,
|
|
929
|
+
"diff": json.loads(diff.model_dump_json()),
|
|
930
|
+
"metadata": {
|
|
931
|
+
"duration_ms": duration_ms,
|
|
932
|
+
"language": diff.language,
|
|
933
|
+
"change_count": len(diff.changes),
|
|
934
|
+
"style_only": diff.is_style_only,
|
|
935
|
+
"guardrail_violation_count": len(diff.guardrail_violations),
|
|
936
|
+
},
|
|
937
|
+
})
|
|
938
|
+
except FileNotFoundError as exc:
|
|
939
|
+
send_fn(
|
|
940
|
+
self._error_response(
|
|
941
|
+
request.seq,
|
|
942
|
+
"file_not_found",
|
|
943
|
+
str(exc),
|
|
944
|
+
op="diff",
|
|
945
|
+
)
|
|
946
|
+
)
|
|
947
|
+
except Exception as exc:
|
|
948
|
+
logger.warning(
|
|
949
|
+
"LiveServer diff error for seq=%d: %s",
|
|
950
|
+
request.seq,
|
|
951
|
+
exc,
|
|
952
|
+
exc_info=True,
|
|
953
|
+
)
|
|
954
|
+
send_fn(self._error_response(request.seq, "diff_error", str(exc), op="diff"))
|
|
955
|
+
|
|
956
|
+
def _compute_diff(
|
|
957
|
+
self,
|
|
958
|
+
source: LiveBufferSource,
|
|
959
|
+
request: _ParsedRequest,
|
|
960
|
+
) -> Any:
|
|
961
|
+
"""Return the ``SemanticDiff`` for a non-streaming request.
|
|
962
|
+
|
|
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.
|
|
967
|
+
"""
|
|
968
|
+
from intentumdiff import rust_core
|
|
969
|
+
from intentumdiff.core.models import SemanticDiff
|
|
970
|
+
|
|
971
|
+
# Diagnostics mode requires the full Python pipeline (per try_rust_core_batch_diffs);
|
|
972
|
+
# the native handler only serves the certified fast path, so skip it when diagnostics
|
|
973
|
+
# are on. (For a mocked differ in tests, `_config.diagnostics` is truthy -> skip.)
|
|
974
|
+
if not getattr(self._differ._config, "diagnostics", False):
|
|
975
|
+
native = rust_core.live_handle_diff(
|
|
976
|
+
self._repo_path,
|
|
977
|
+
request.path,
|
|
978
|
+
request.ref,
|
|
979
|
+
request.content,
|
|
980
|
+
self._differ._config.model_dump_json(),
|
|
981
|
+
_wasm_dir(),
|
|
982
|
+
)
|
|
983
|
+
if "diff" in native:
|
|
984
|
+
return SemanticDiff.model_validate(native["diff"])
|
|
985
|
+
return self._differ.diff(source)
|
|
986
|
+
|
|
987
|
+
def _compute_review(
|
|
988
|
+
self,
|
|
989
|
+
review_config: Any,
|
|
990
|
+
commit_differ: Any,
|
|
991
|
+
old_ref: str,
|
|
992
|
+
new_ref: str,
|
|
993
|
+
) -> Any:
|
|
994
|
+
"""Return the ``CommitDiff`` for a non-streaming review.
|
|
995
|
+
|
|
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``.
|
|
1000
|
+
"""
|
|
1001
|
+
from intentumdiff import rust_core
|
|
1002
|
+
from intentumdiff.core.models import CommitDiff
|
|
1003
|
+
|
|
1004
|
+
if not getattr(review_config, "diagnostics", False):
|
|
1005
|
+
native = rust_core.live_handle_review(
|
|
1006
|
+
self._repo_path,
|
|
1007
|
+
old_ref,
|
|
1008
|
+
new_ref,
|
|
1009
|
+
review_config.model_dump_json(),
|
|
1010
|
+
_wasm_dir(),
|
|
1011
|
+
)
|
|
1012
|
+
if "commit_diff" in native:
|
|
1013
|
+
return CommitDiff.model_validate(native["commit_diff"])
|
|
1014
|
+
return commit_differ.diff_commit(
|
|
1015
|
+
repo_path=self._repo_path, old_ref=old_ref, new_ref=new_ref
|
|
1016
|
+
)
|
|
1017
|
+
|
|
1018
|
+
def _handle_control_request(
|
|
1019
|
+
self,
|
|
1020
|
+
request: dict[str, Any],
|
|
1021
|
+
send_fn: "Any",
|
|
1022
|
+
) -> bool:
|
|
1023
|
+
op = request.get("op", "diff")
|
|
1024
|
+
if op is None:
|
|
1025
|
+
op = "diff"
|
|
1026
|
+
if op == "diff":
|
|
1027
|
+
return False
|
|
1028
|
+
seq, seq_error = self._request_seq(request)
|
|
1029
|
+
if seq_error is not None:
|
|
1030
|
+
send_fn(seq_error)
|
|
1031
|
+
return True
|
|
1032
|
+
if op == "hello":
|
|
1033
|
+
send_fn({
|
|
1034
|
+
"op": "hello",
|
|
1035
|
+
"seq": seq,
|
|
1036
|
+
"ok": True,
|
|
1037
|
+
"protocol_version": _PROTOCOL_VERSION,
|
|
1038
|
+
"repo_path": self._repo_path,
|
|
1039
|
+
"ref": self._ref,
|
|
1040
|
+
"limits": self._limits(),
|
|
1041
|
+
"capabilities": self._capabilities(),
|
|
1042
|
+
})
|
|
1043
|
+
return True
|
|
1044
|
+
if op == "review":
|
|
1045
|
+
self._process_review_request(request, seq, send_fn)
|
|
1046
|
+
return True
|
|
1047
|
+
if op == "cancel":
|
|
1048
|
+
send_fn(self._cancel_request(request, seq))
|
|
1049
|
+
return True
|
|
1050
|
+
send_fn(self._error_response(seq, "unknown_op", f"unknown op: {op!r}", op=str(op)))
|
|
1051
|
+
return True
|
|
1052
|
+
|
|
1053
|
+
def _process_review_request(
|
|
1054
|
+
self,
|
|
1055
|
+
request: dict[str, Any],
|
|
1056
|
+
seq: int,
|
|
1057
|
+
send_fn: "Any",
|
|
1058
|
+
) -> None:
|
|
1059
|
+
"""Run a saved-snapshot commit review and send a protocol-v2 response."""
|
|
1060
|
+
# Ref/stream validation lives in the core; orchestration below stays Python.
|
|
1061
|
+
from intentumdiff import rust_core
|
|
1062
|
+
|
|
1063
|
+
review = rust_core.live_parse_review_request(request, self._ref, seq)
|
|
1064
|
+
if "error" in review:
|
|
1065
|
+
send_fn(review["error"])
|
|
1066
|
+
return
|
|
1067
|
+
parsed = review["parsed"]
|
|
1068
|
+
old_ref = parsed["old_ref"]
|
|
1069
|
+
new_ref = parsed["new_ref"]
|
|
1070
|
+
stream = parsed["stream"]
|
|
1071
|
+
|
|
1072
|
+
with self._lock:
|
|
1073
|
+
self._latest_review_seq = max(self._latest_review_seq, seq)
|
|
1074
|
+
|
|
1075
|
+
start = time.perf_counter()
|
|
1076
|
+
try:
|
|
1077
|
+
from intentumdiff.core.commit_differ import CommitDiffer
|
|
1078
|
+
|
|
1079
|
+
review_config = self._differ._config.model_copy()
|
|
1080
|
+
review_registry = self._differ._registry
|
|
1081
|
+
review_fuel_capped = False
|
|
1082
|
+
if review_config.plugin_fuel == -1:
|
|
1083
|
+
review_config.plugin_fuel = _REVIEW_FUEL_WHEN_LIVE_UNLIMITED
|
|
1084
|
+
review_registry = None
|
|
1085
|
+
review_fuel_capped = True
|
|
1086
|
+
|
|
1087
|
+
commit_differ = CommitDiffer(
|
|
1088
|
+
config=review_config,
|
|
1089
|
+
registry=review_registry,
|
|
1090
|
+
)
|
|
1091
|
+
if stream:
|
|
1092
|
+
commit_diff = self._run_streaming_review(
|
|
1093
|
+
commit_differ=commit_differ,
|
|
1094
|
+
seq=seq,
|
|
1095
|
+
old_ref=old_ref,
|
|
1096
|
+
new_ref=new_ref,
|
|
1097
|
+
send_fn=send_fn,
|
|
1098
|
+
)
|
|
1099
|
+
else:
|
|
1100
|
+
commit_diff = self._compute_review(
|
|
1101
|
+
review_config, commit_differ, old_ref, new_ref
|
|
1102
|
+
)
|
|
1103
|
+
with self._lock:
|
|
1104
|
+
if seq < self._latest_review_seq:
|
|
1105
|
+
return
|
|
1106
|
+
duration_ms = round((time.perf_counter() - start) * 1000, 3)
|
|
1107
|
+
send_fn({
|
|
1108
|
+
"op": "review",
|
|
1109
|
+
"seq": seq,
|
|
1110
|
+
"ok": True,
|
|
1111
|
+
"commit_diff": json.loads(commit_diff.model_dump_json()),
|
|
1112
|
+
"metadata": {
|
|
1113
|
+
"duration_ms": duration_ms,
|
|
1114
|
+
"file_count": len(commit_diff.file_diffs),
|
|
1115
|
+
"guardrail_violation_count": len(commit_diff.guardrail_violations),
|
|
1116
|
+
"cross_file_change_count": len(commit_diff.cross_file_changes),
|
|
1117
|
+
"old_ref": old_ref,
|
|
1118
|
+
"new_ref": new_ref,
|
|
1119
|
+
"review_fuel_capped": review_fuel_capped,
|
|
1120
|
+
"review_plugin_fuel": review_config.plugin_fuel,
|
|
1121
|
+
"streamed": stream,
|
|
1122
|
+
},
|
|
1123
|
+
})
|
|
1124
|
+
except _ReviewCancelled:
|
|
1125
|
+
return
|
|
1126
|
+
except Exception as exc:
|
|
1127
|
+
logger.warning(
|
|
1128
|
+
"LiveServer review error for seq=%d: %s",
|
|
1129
|
+
seq,
|
|
1130
|
+
exc,
|
|
1131
|
+
exc_info=True,
|
|
1132
|
+
)
|
|
1133
|
+
send_fn(self._error_response(seq, "review_error", str(exc), op="review"))
|
|
1134
|
+
|
|
1135
|
+
def _run_streaming_review(
|
|
1136
|
+
self,
|
|
1137
|
+
*,
|
|
1138
|
+
commit_differ: Any,
|
|
1139
|
+
seq: int,
|
|
1140
|
+
old_ref: str,
|
|
1141
|
+
new_ref: str,
|
|
1142
|
+
send_fn: Any,
|
|
1143
|
+
) -> Any:
|
|
1144
|
+
"""Emit per-file ``review_file`` events then return the final CommitDiff."""
|
|
1145
|
+
from intentumdiff.core.commit_differ import FileDiffError, FileDiffResult
|
|
1146
|
+
|
|
1147
|
+
results: list[FileDiffResult] = []
|
|
1148
|
+
errors: list[FileDiffError] = []
|
|
1149
|
+
for index, item in enumerate(
|
|
1150
|
+
commit_differ.iter_file_diffs(
|
|
1151
|
+
repo_path=self._repo_path,
|
|
1152
|
+
old_ref=old_ref,
|
|
1153
|
+
new_ref=new_ref,
|
|
1154
|
+
),
|
|
1155
|
+
start=1,
|
|
1156
|
+
):
|
|
1157
|
+
with self._lock:
|
|
1158
|
+
if seq < self._latest_review_seq:
|
|
1159
|
+
raise _ReviewCancelled(seq)
|
|
1160
|
+
if isinstance(item, FileDiffResult):
|
|
1161
|
+
results.append(item)
|
|
1162
|
+
send_fn({
|
|
1163
|
+
"op": "review_file",
|
|
1164
|
+
"seq": seq,
|
|
1165
|
+
"ok": True,
|
|
1166
|
+
"file_diff": json.loads(item.file_diff.model_dump_json()),
|
|
1167
|
+
"old_filename": item.file_diff.old_filename,
|
|
1168
|
+
"new_filename": item.file_diff.new_filename,
|
|
1169
|
+
"index": index,
|
|
1170
|
+
})
|
|
1171
|
+
else:
|
|
1172
|
+
errors.append(item)
|
|
1173
|
+
|
|
1174
|
+
return commit_differ.finalize_commit_diff(
|
|
1175
|
+
results,
|
|
1176
|
+
errors,
|
|
1177
|
+
old_ref=old_ref,
|
|
1178
|
+
new_ref=new_ref,
|
|
1179
|
+
repo_path=self._repo_path,
|
|
1180
|
+
)
|
|
1181
|
+
|
|
1182
|
+
def _parse_diff_request(
|
|
1183
|
+
self,
|
|
1184
|
+
request: dict[str, Any],
|
|
1185
|
+
) -> tuple[_ParsedRequest | None, dict[str, Any] | None]:
|
|
1186
|
+
# Field validation (seq / path guard / content cap / ref / stream / deltas type+count)
|
|
1187
|
+
# lives in the core; the shell only builds the EditDelta DTOs from the raw deltas.
|
|
1188
|
+
from intentumdiff import rust_core
|
|
1189
|
+
|
|
1190
|
+
result = rust_core.live_parse_diff_request(request, self._ref)
|
|
1191
|
+
if "error" in result:
|
|
1192
|
+
return None, result["error"]
|
|
1193
|
+
parsed = result["parsed"]
|
|
1194
|
+
|
|
1195
|
+
raw_deltas: list[dict[str, Any]] = parsed.get("deltas") or []
|
|
1196
|
+
edit_deltas: list[EditDelta] | None = None
|
|
1197
|
+
if raw_deltas:
|
|
1198
|
+
try:
|
|
1199
|
+
edit_deltas = [EditDelta.model_validate(delta) for delta in raw_deltas]
|
|
1200
|
+
except Exception as exc:
|
|
1201
|
+
logger.warning(
|
|
1202
|
+
"Invalid edit deltas in request for %r: %s", parsed["path"], exc
|
|
1203
|
+
)
|
|
1204
|
+
|
|
1205
|
+
return (
|
|
1206
|
+
_ParsedRequest(
|
|
1207
|
+
op="diff",
|
|
1208
|
+
seq=int(parsed["seq"]),
|
|
1209
|
+
path=parsed["path"],
|
|
1210
|
+
content=parsed["content"],
|
|
1211
|
+
ref=parsed["ref"],
|
|
1212
|
+
edit_deltas=edit_deltas,
|
|
1213
|
+
stream=parsed["stream"],
|
|
1214
|
+
),
|
|
1215
|
+
None,
|
|
1216
|
+
)
|
|
1217
|
+
|
|
1218
|
+
def _request_seq(
|
|
1219
|
+
self,
|
|
1220
|
+
request: dict[str, Any],
|
|
1221
|
+
) -> tuple[int, dict[str, Any] | None]:
|
|
1222
|
+
from intentumdiff import rust_core
|
|
1223
|
+
|
|
1224
|
+
result = rust_core.live_request_seq(request)
|
|
1225
|
+
if "error" in result:
|
|
1226
|
+
return 0, result["error"]
|
|
1227
|
+
return int(result["seq"]), None
|
|
1228
|
+
|
|
1229
|
+
def _normalise_request_path(
|
|
1230
|
+
self,
|
|
1231
|
+
path: str,
|
|
1232
|
+
seq: int,
|
|
1233
|
+
) -> tuple[str, dict[str, Any] | None]:
|
|
1234
|
+
from intentumdiff import rust_core
|
|
1235
|
+
|
|
1236
|
+
result = rust_core.live_normalise_request_path(path)
|
|
1237
|
+
if result["ok"]:
|
|
1238
|
+
return result["path"], None
|
|
1239
|
+
return "", self._error_response(
|
|
1240
|
+
seq, result["code"], result["message"], op="diff"
|
|
1241
|
+
)
|
|
1242
|
+
|
|
1243
|
+
def _cancel_request(self, request: dict[str, Any], seq: int) -> dict[str, Any]:
|
|
1244
|
+
path_raw = request.get("path")
|
|
1245
|
+
cancelled = 0
|
|
1246
|
+
with self._lock:
|
|
1247
|
+
if isinstance(path_raw, str) and path_raw:
|
|
1248
|
+
path, _ = self._normalise_request_path(path_raw, seq)
|
|
1249
|
+
timer = self._timers.pop(path, None)
|
|
1250
|
+
pending = self._timer_requests.pop(path, None)
|
|
1251
|
+
if timer is not None:
|
|
1252
|
+
timer.cancel()
|
|
1253
|
+
cancelled += 1
|
|
1254
|
+
stale_after = seq if seq else ((pending.seq + 1) if pending else 1)
|
|
1255
|
+
self._latest_seq[path] = max(self._latest_seq.get(path, 0), stale_after)
|
|
1256
|
+
elif seq:
|
|
1257
|
+
self._latest_review_seq = max(self._latest_review_seq, seq + 1)
|
|
1258
|
+
for path, pending in list(self._timer_requests.items()):
|
|
1259
|
+
if pending.seq <= seq:
|
|
1260
|
+
timer = self._timers.pop(path, None)
|
|
1261
|
+
self._timer_requests.pop(path, None)
|
|
1262
|
+
if timer is not None:
|
|
1263
|
+
timer.cancel()
|
|
1264
|
+
cancelled += 1
|
|
1265
|
+
self._latest_seq[path] = max(self._latest_seq.get(path, 0), seq + 1)
|
|
1266
|
+
return {"op": "cancel", "seq": seq, "ok": True, "cancelled": cancelled}
|
|
1267
|
+
|
|
1268
|
+
def _is_stale(self, request: _ParsedRequest) -> bool:
|
|
1269
|
+
with self._lock:
|
|
1270
|
+
return request.seq < self._latest_seq.get(request.path, 0)
|
|
1271
|
+
|
|
1272
|
+
def _limits(self) -> dict[str, int]:
|
|
1273
|
+
from intentumdiff import rust_core
|
|
1274
|
+
|
|
1275
|
+
return rust_core.live_limits()
|
|
1276
|
+
|
|
1277
|
+
def _capabilities(self) -> dict[str, Any]:
|
|
1278
|
+
from intentumdiff import rust_core
|
|
1279
|
+
|
|
1280
|
+
return rust_core.live_capabilities()
|
|
1281
|
+
|
|
1282
|
+
def _error_response(
|
|
1283
|
+
self,
|
|
1284
|
+
seq: int,
|
|
1285
|
+
code: str,
|
|
1286
|
+
message: str,
|
|
1287
|
+
*,
|
|
1288
|
+
op: str = "error",
|
|
1289
|
+
) -> dict[str, Any]:
|
|
1290
|
+
from intentumdiff import rust_core
|
|
1291
|
+
|
|
1292
|
+
return rust_core.live_error_response(seq, code, message, op)
|
|
1293
|
+
|
|
1294
|
+
|
|
1295
|
+
# ---------------------------------------------------------------------------
|
|
1296
|
+
# Wire helpers
|
|
1297
|
+
# ---------------------------------------------------------------------------
|
|
1298
|
+
|
|
1299
|
+
def _write_line(stream: "Any", obj: dict[str, Any]) -> None:
|
|
1300
|
+
"""Write *obj* as a JSON line to a text stream."""
|
|
1301
|
+
try:
|
|
1302
|
+
stream.write(json.dumps(obj, ensure_ascii=True) + "\n")
|
|
1303
|
+
stream.flush()
|
|
1304
|
+
except OSError:
|
|
1305
|
+
pass
|
|
1306
|
+
|
|
1307
|
+
|
|
1308
|
+
def _write_line_bytes(sock: socket.socket, obj: dict[str, Any]) -> None:
|
|
1309
|
+
"""Write *obj* as a JSON line to a socket."""
|
|
1310
|
+
try:
|
|
1311
|
+
data = (json.dumps(obj, ensure_ascii=True) + "\n").encode("utf-8")
|
|
1312
|
+
sock.sendall(data)
|
|
1313
|
+
except OSError:
|
|
1314
|
+
pass
|