diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 8d1b418..677806f 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "java-functional-lsp", "description": "Java LSP with functional programming rules enforcement — null safety, immutability, no exceptions, Spring best practices. Wraps jdtls for full Java language support.", - "version": "0.4.3", + "version": "0.4.4", "lspServers": { "java-functional": { "command": "java-functional-lsp", diff --git a/README.md b/README.md index 1793b58..d62566a 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,7 @@ moving on. Fix any type errors or missing imports immediately. | "java-functional-lsp not found" | Run `brew install aviadshiber/tap/java-functional-lsp` | | Plugin not active | Run `claude plugin list` to verify, then `/reload-plugins` | | Diagnostics slow on first open | Normal — tree-sitter parses on first load, then incremental | -| Java errors show up one tool call after the edit | Claude Code doesn't wait for LSP diagnostics after Edit/Write ([anthropics/claude-code#93321](https://github.com/anthropics/claude-code/issues/93321)); jdtls results arrive with the next tool result. See [Fresh jdtls diagnostics after edits](#fresh-jdtls-diagnostics-after-edits) | +| Java errors show up one tool call after the edit | Claude Code doesn't wait for LSP diagnostics after Edit/Write ([anthropics/claude-code#93321](https://github.com/anthropics/claude-code/issues/93321)). The plugin's hook waits up to 3s for them; if jdtls is slower (large projects), raise `JAVA_FUNCTIONAL_LSP_HOOK_WAIT` (max 4). See [Fresh jdtls diagnostics after edits](#fresh-jdtls-diagnostics-after-edits) | ### Other Editors @@ -317,6 +317,11 @@ jdtls re-validates a file 0.4–2.4s after the last edit to *any* file, and its | `hold-all` | Other editors | Nothing is published for the file until jdtls has re-validated (no flickering squiggles) | | `off` | — | Previous behavior: custom diagnostics plus the last known jdtls diagnostics after 150ms | +With Claude Code two more things happen: + +- **The plugin's PostToolUse hook waits for fresh results.** Claude Code attaches diagnostics as soon as its PostToolUse hooks finish, without waiting for the server ([anthropics/claude-code#93321](https://github.com/anthropics/claude-code/issues/93321)). The server records when it last published final diagnostics for each file, and `hooks/post_tool_lint.py` waits until that is newer than the edit (at most `JAVA_FUNCTIONAL_LSP_HOOK_WAIT` seconds, default 3, max 4), so jdtls's result for the edit arrives in the same tool result. The markers live in a private per-user temp directory and contain only a timestamp. +- **jdtls gets a didSave after each edit.** Claude Code writes the file itself; when the edited buffer matches the file on disk, the server forwards a didSave. Without it, jdtls can re-check dependent files against the old version of the edited one (e.g. a caller keeps reporting a constructor's old arity) and never correct them. + If jdtls doesn't publish in time (3s after the last edit, stretched when jdtls is slow, 10s at most), the last known jdtls diagnostics are used. Files whose module is still being imported, and files matched by `java.diagnostic.filter`, are never held. While you edit the same file in quick succession, its diagnostics update only once the burst settles. Environment variables: @@ -324,6 +329,7 @@ Environment variables: | Variable | Values | Effect | |----------|--------|--------| | `JAVA_FUNCTIONAL_LSP_DIAG_HOLD` | `custom-first`, `hold-all`, `off` | Overrides the mode above; `off` restores the previous behavior | +| `JAVA_FUNCTIONAL_LSP_HOOK_WAIT` | seconds, `0`–`4` (default `3`) | How long the Claude Code PostToolUse hook waits for fresh jdtls diagnostics; `0` disables the wait | | `JAVA_FUNCTIONAL_LSP_LOG_LEVEL` | `DEBUG`, `INFO` (default), `WARNING` | Verbosity of java-functional-lsp's own logs; `DEBUG` adds one line per publish decision (file name, trigger, counts). Library logging (pygls) is unaffected — note that pygls already logs the JSON it sends, including diagnostic messages, at `INFO` | The log reports `jdtls freshness: released=… too_early=… timeout=… late_correction=…` every 100 decisions and when jdtls stops. Repeated `timeout` lines mean jdtls is slow or stuck on that module. A growing `late_correction` count means jdtls results were released too early. diff --git a/hooks/post_tool_lint.py b/hooks/post_tool_lint.py index ac4dc7e..5ac1864 100755 --- a/hooks/post_tool_lint.py +++ b/hooks/post_tool_lint.py @@ -3,7 +3,9 @@ Reads the Claude Code PostToolUse JSON payload on stdin, runs java-functional-lsp on the edited file, and emits diagnostics as ``hookSpecificOutput.additionalContext`` -so the agent sees them in context and can fix them immediately (issue #70). +so the agent sees them in context and can fix them immediately (issue #70). Before +returning it waits (bounded) for the running language server to publish fresh jdtls +diagnostics for the file, so Claude Code attaches current ones to this edit (#109). Failure-safe by design: every path exits 0 — a linter problem must never break the editing session. Prefers the fast in-process import; falls back to the CLI when the @@ -12,14 +14,101 @@ from __future__ import annotations +import getpass +import hashlib import json +import os import signal +import stat import subprocess import sys +import tempfile +import time from pathlib import Path TIMEOUT_SECONDS = 5 # hard cap; single-file analysis is typically <200ms MAX_DIAGNOSTICS = 25 # keep additionalContext bounded +POLL_SECONDS = 0.05 +DEFAULT_WAIT_SECONDS = 3.0 +MAX_WAIT_SECONDS = 4.0 +EXIT_MARGIN_SECONDS = 0.5 # finish well before SIGALRM so the lint output is printed +MARKER_MAX_BYTES = 128 + + +def _fresh_wait_seconds() -> float: + try: + wait = float(os.environ.get("JAVA_FUNCTIONAL_LSP_HOOK_WAIT", DEFAULT_WAIT_SECONDS)) + except ValueError: + return DEFAULT_WAIT_SECONDS + return max(0.0, min(wait, MAX_WAIT_SECONDS)) + + +def _user() -> str: + try: + return getpass.getuser() + except Exception: + return str(os.getuid()) if hasattr(os, "getuid") else "user" + + +def _marker_path(file_path: str) -> Path: + """Must match java_functional_lsp.freshness_marker.marker_path (a test checks).""" + digest = hashlib.sha256(os.path.realpath(file_path).encode()).hexdigest()[:32] + return Path(tempfile.gettempdir()) / f"java-functional-lsp-{_user()}" / "fresh" / digest + + +def _owned(st: os.stat_result) -> bool: + return not hasattr(os, "getuid") or st.st_uid == os.getuid() + + +def _read_marker(marker: Path) -> tuple[int, str] | None: + """(server pid, content digest), or None unless the marker and its dirs are private and ours.""" + try: + for level in (marker.parent.parent, marker.parent): + st = os.lstat(level) + if not stat.S_ISDIR(st.st_mode) or not _owned(st) or st.st_mode & 0o077: + return None + fd = os.open(marker, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + try: + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode) or not _owned(st): + return None + pid, digest = os.read(fd, MARKER_MAX_BYTES).decode().split() + finally: + os.close(fd) + server_pid = int(pid) + return (server_pid, digest) if server_pid > 0 else None # kill(0|-n, 0) targets groups + except (OSError, ValueError): + return None + + +def _server_alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except PermissionError: + return True + except OSError: + return False + return True + + +def _wait_for_fresh_diagnostics(path: Path, budget: float) -> None: + """Wait until the language server has published final diagnostics for this edit. + + Claude Code attaches LSP diagnostics right after PostToolUse hooks finish, but jdtls + needs 0.4-2.4s to re-validate (#109). On each final publish the server records its pid + and a hash of the content it analyzed; waiting until that hash matches the file puts + fresh results in this tool result. No marker, or a dead server, means nobody will + publish — don't wait. + """ + marker = _marker_path(str(path)) + current = _read_marker(marker) + if current is None or not _server_alive(current[0]): + return + want = hashlib.sha256(path.read_bytes()).hexdigest() + deadline = time.monotonic() + min(_fresh_wait_seconds(), budget) + while current is not None and current[1] != want and time.monotonic() < deadline: + time.sleep(POLL_SECONDS) + current = _read_marker(marker) def _lint_in_process(path: Path) -> list[str] | None: @@ -48,6 +137,7 @@ def _lint_via_cli(path: Path) -> list[str]: def main() -> None: + started = time.monotonic() hook_input = json.load(sys.stdin) file_path = (hook_input.get("tool_input") or {}).get("file_path", "") if not file_path.endswith(".java"): @@ -59,6 +149,11 @@ def main() -> None: lines = _lint_in_process(path) if lines is None: lines = _lint_via_cli(path) + try: + budget = TIMEOUT_SECONDS - EXIT_MARGIN_SECONDS - (time.monotonic() - started) + _wait_for_fresh_diagnostics(path, budget=budget) + except Exception: + pass # a marker problem must never suppress the lint output below if not lines: return # clean file: stay silent, no per-edit context noise diff --git a/pyproject.toml b/pyproject.toml index 6db843d..8dd39f7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "java-functional-lsp" -version = "0.12.1" +version = "0.13.0" description = "Java LSP server enforcing functional programming best practices — null safety, immutability, no exceptions" readme = "README.md" license = { text = "MIT" } diff --git a/src/java_functional_lsp/__init__.py b/src/java_functional_lsp/__init__.py index ffef784..d7749e3 100644 --- a/src/java_functional_lsp/__init__.py +++ b/src/java_functional_lsp/__init__.py @@ -1,3 +1,3 @@ """java-functional-lsp: A Java LSP server enforcing functional programming best practices.""" -__version__ = "0.12.1" +__version__ = "0.13.0" diff --git a/src/java_functional_lsp/freshness_marker.py b/src/java_functional_lsp/freshness_marker.py new file mode 100644 index 0000000..480ab86 --- /dev/null +++ b/src/java_functional_lsp/freshness_marker.py @@ -0,0 +1,78 @@ +"""Per-file "diagnostics are final" markers for the Claude Code PostToolUse hook (#109). + +Claude Code collects LSP diagnostics right after its PostToolUse hooks finish, without +waiting for the server. When the server publishes final diagnostics for a file (fresh +jdtls results merged in) it records the server pid and a hash of the content it analyzed; +``hooks/post_tool_lint.py`` waits until the hash matches the file on disk, so the fresh +set lands in the same tool result. A hash (not a time) means a publish for an older +version of the file can never satisfy the hook, and the pid lets the hook skip waiting +when the server that wrote the marker is gone. + +The hook keeps its own copy of :func:`marker_path` and of the directory checks (it may run +without this package importable); tests keep the two in sync. +""" + +from __future__ import annotations + +import getpass +import hashlib +import os +import stat +import tempfile +from pathlib import Path + +#: Written at didOpen: never equals a content hash, so the hook waits for jdtls's first result. +OPENING = "opening" + +_validated: set[Path] = set() + + +def _user() -> str: + try: + return getpass.getuser() + except Exception: # containers without a passwd entry: KeyError (<3.13) / OSError (3.13+) + return str(os.getuid()) if hasattr(os, "getuid") else "user" + + +def marker_dir() -> Path: + return Path(tempfile.gettempdir()) / f"java-functional-lsp-{_user()}" / "fresh" + + +def marker_path(file_path: str) -> Path: + digest = hashlib.sha256(os.path.realpath(file_path).encode()).hexdigest()[:32] + return marker_dir() / digest + + +def content_digest(content: bytes) -> str: + return hashlib.sha256(content).hexdigest() + + +def _ensure_private_dir(path: Path) -> bool: + """Create *path* if needed; True only for a real directory we own with no group/other access.""" + path.mkdir(mode=0o700, exist_ok=True) + st = os.lstat(path) # lstat: a symlink is never S_ISDIR + if not stat.S_ISDIR(st.st_mode) or (hasattr(os, "getuid") and st.st_uid != os.getuid()): + return False + if st.st_mode & 0o077: + os.chmod(path, 0o700) + return True + + +def write_marker(file_path: str, digest: str) -> None: + """Record that final diagnostics for *file_path* were published for content *digest*. Never raises.""" + try: + directory = marker_dir() + if directory not in _validated: + # Check each level before creating below it, so nothing lands behind a + # symlink planted in a shared temp dir. + if not (_ensure_private_dir(directory.parent) and _ensure_private_dir(directory)): + return + _validated.add(directory) + target = marker_path(file_path) + tmp = target.with_name(f"{target.name}.{os.getpid()}.tmp") + flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0) + with os.fdopen(os.open(tmp, flags, 0o600), "w") as f: + f.write(f"{os.getpid()} {digest}") + os.replace(tmp, target) + except Exception: + _validated.clear() diff --git a/src/java_functional_lsp/server.py b/src/java_functional_lsp/server.py index 937edf5..0e47f95 100644 --- a/src/java_functional_lsp/server.py +++ b/src/java_functional_lsp/server.py @@ -14,6 +14,7 @@ import logging import os import re +import stat import sys import time from collections import Counter, OrderedDict @@ -47,6 +48,7 @@ StaticCapabilityBuilder, ) from .fixes import get_fix, get_fix_registry_keys +from .freshness_marker import OPENING, content_digest, write_marker from .proxy import JdtlsProxy, _module_snapshot_path, _resolve_module_uri logger = logging.getLogger(__name__) @@ -119,7 +121,14 @@ def _normalize_uri(uri: str) -> str: _HOLD_ALL = "hold-all" _HOLD_CUSTOM_FIRST = "custom-first" _HOLD_MODES = (_HOLD_OFF, _HOLD_ALL, _HOLD_CUSTOM_FIRST) -_CUSTOM_FIRST_CLIENTS = ("Claude Code",) +_AGENT_HOST_CLIENTS = ("Claude Code",) + + +def _is_agent_host(client_name: str) -> bool: + """Agent hosts write files before didChange and read diagnostics right after their hooks.""" + return any(token in client_name for token in _AGENT_HOST_CLIENTS) + + _CUSTOM_SOURCE = "java-functional-lsp" @@ -278,6 +287,10 @@ def __init__(self) -> None: self._user_suppress_patterns: list[re.Pattern[str]] = [] self._skip_jdtls: bool = False self._hold_mode: str = _HOLD_OFF + # Agent host (Claude Code): see _forward_save_if_on_disk and _stamp_final_publish. + self._agent_host: bool = False + # Opened files (normalized) opened or edited since their last freshness marker. + self._marker_dirty: set[str] = set() self._skip_jdtls_registration: bool = False self._init_generation: int = 0 # Capability entries the negotiator decided to register dynamically @@ -318,6 +331,7 @@ def _record_opened(self, uri: str) -> None: if len(self._session_opened_uris) > _MAX_OPENED_URIS: evicted, _ = self._session_opened_uris.popitem(last=False) self._module_uris.pop(evicted, None) + self._marker_dirty.discard(evicted) _freshness.forget(evicted) def _on_jdtls_diagnostics(self, uri: str, diagnostics: list[Any]) -> None: @@ -702,6 +716,8 @@ def on_initialize(params: lsp.InitializeParams) -> lsp.InitializeResult: _jdtls_capabilities_registered = False _release_all_holds() server._hold_mode = _resolve_hold_mode(client_name) + server._agent_host = _is_agent_host(client_name) + server._marker_dirty.clear() logger.info("jdtls diagnostics hold mode: %s", server._hold_mode) jdtls_override = os.environ.get("JAVA_FUNCTIONAL_LSP_JDTLS", "").strip().lower() @@ -841,6 +857,55 @@ def _analyze_and_publish(uri: str, *, include_jdtls: bool = True, trigger: str = "publish %s trigger=%s java=%d custom=%d", Path(client_uri).name, trigger, java, len(diagnostics) - java ) server.text_document_publish_diagnostics(lsp.PublishDiagnosticsParams(uri=client_uri, diagnostics=diagnostics)) + if include_jdtls and server._agent_host and _is_final(trigger): + _stamp_final_publish(client_uri, doc.source) + + +def _is_final(trigger: str) -> bool: + """Whether a publish carries jdtls results for the current content (nothing better is coming).""" + if trigger in ("jdtls", "timeout"): + return True + # With the hold on, a change/save publish only happens when the file isn't held, i.e. + # no fresher jdtls result will follow. With it off, it carries the previous edit's set. + return trigger in ("change", "save") and (server._hold_mode != _HOLD_OFF or not server._proxy.is_available) + + +def _stamp_final_publish(client_uri: str, source: str) -> None: + """Tell the Claude Code hook that diagnostics for *source* are published (see freshness_marker).""" + key = _normalize_uri(client_uri) + fs_path = to_fs_path(client_uri) + if key not in server._marker_dirty or not fs_path: + return # background republish of an unedited file: the hook only waits on edits + server._marker_dirty.discard(key) + write_marker(fs_path, content_digest(source.encode())) + + +def _agent_did_save_enabled() -> bool: + return os.environ.get("JAVA_FUNCTIONAL_LSP_AGENT_DIDSAVE", "").strip().lower() != "off" + + +def _forward_save_if_on_disk(uri: str) -> None: + """Send jdtls a didSave when the edited buffer matches the file on disk. + + Agent hosts write the file themselves and may not send didSave; without it jdtls can + re-validate dependent files against the old version of the edited one and never + correct them (#109: stale in ~2 of 5 runs, never with didSave). jdtls's handleSaved + only reloads the working copy from disk, which here equals the buffer. + """ + try: + fs_path = to_fs_path(uri) + if not fs_path: + return + source = server.workspace.get_text_document(uri).source.encode() + st = os.stat(fs_path) + if not stat.S_ISREG(st.st_mode) or st.st_size != len(source): + return + if Path(fs_path).read_bytes() != source: + logger.debug("didSave skipped for %s: disk content differs from the buffer", Path(fs_path).name) + return + _forward_or_queue("textDocument/didSave", {"textDocument": {"uri": uri}}) + except Exception as e: + logger.debug("didSave check failed for %s: %s", Path(uri).name, type(e).__name__) def _resolve_hold_mode(client_name: str) -> str: @@ -849,7 +914,7 @@ def _resolve_hold_mode(client_name: str) -> str: return override if override: logger.warning("Unknown JAVA_FUNCTIONAL_LSP_DIAG_HOLD value %r; expected %s", override, "/".join(_HOLD_MODES)) - return _HOLD_CUSTOM_FIRST if any(token in client_name for token in _CUSTOM_FIRST_CLIENTS) else _HOLD_ALL + return _HOLD_CUSTOM_FIRST if _is_agent_host(client_name) else _HOLD_ALL def _matches_diagnostic_filter(uri: str) -> bool: @@ -969,6 +1034,13 @@ async def on_did_open(params: lsp.DidOpenTextDocumentParams) -> None: # Must precede any await: same-loop jdtls diagnostic callbacks need to # observe this URI before they arrive to avoid the publish getting gated. server._record_opened(uri) + if server._agent_host and not server._skip_jdtls: + # A placeholder the file never hashes to: the hook waits for jdtls's first result + # instead of taking this open's (jdtls-less) publish as final. + fs_path = to_fs_path(uri) + if fs_path: + server._marker_dirty.add(_normalize_uri(uri)) + write_marker(fs_path, OPENING) if server._skip_jdtls: # Skip all jdtls forwarding — custom diagnostics only. @@ -999,12 +1071,19 @@ async def on_did_open(params: lsp.DidOpenTextDocumentParams) -> None: async def on_did_change(params: lsp.DidChangeTextDocumentParams) -> None: """Forward to jdtls and schedule debounced re-analysis.""" uri = params.text_document.uri - if _forward_or_queue("textDocument/didChange", _serialize_params(params)): + forwarded = _forward_or_queue("textDocument/didChange", _serialize_params(params)) + if forwarded: _track_forwarded_edit(uri) # Cancel pending validation, schedule new one (150ms debounce for IDE typing) if uri in _pending: _pending[uri].cancel() _pending[uri] = asyncio.create_task(_deferred_validate(uri)) + if server._agent_host: + key = _normalize_uri(uri) + if key in server._session_opened_uris: + server._marker_dirty.add(key) + if forwarded and _agent_did_save_enabled(): + _forward_save_if_on_disk(uri) @server.feature(lsp.TEXT_DOCUMENT_DID_SAVE) diff --git a/tests/conftest.py b/tests/conftest.py index e232114..c3b107c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,6 +19,8 @@ def isolate_diagnostics_hold(monkeypatch: pytest.MonkeyPatch) -> None: from java_functional_lsp import server as srv_mod monkeypatch.setattr(srv_mod.server, "_hold_mode", srv_mod._HOLD_OFF) + monkeypatch.setattr(srv_mod.server, "_agent_host", False) + monkeypatch.setattr(srv_mod.server, "_marker_dirty", set()) monkeypatch.setattr(srv_mod, "_freshness", srv_mod._JdtlsFreshness()) monkeypatch.setattr(srv_mod, "_hold_events", {}) diff --git a/tests/test_diagnostics_freshness.py b/tests/test_diagnostics_freshness.py index ebdb086..dbfeaf2 100644 --- a/tests/test_diagnostics_freshness.py +++ b/tests/test_diagnostics_freshness.py @@ -5,6 +5,7 @@ import asyncio import logging from collections.abc import AsyncIterator, Callable +from pathlib import Path from typing import Any from unittest.mock import AsyncMock, MagicMock, patch @@ -13,6 +14,7 @@ from pygls.workspace import Workspace from java_functional_lsp import server as srv_mod +from java_functional_lsp.freshness_marker import OPENING, content_digest from java_functional_lsp.proxy import JdtlsProxy from java_functional_lsp.server import ( _HOLD_ALL, @@ -580,6 +582,144 @@ async def test_encoded_jdtls_uri_releases_hold_and_publishes_client_uri(self, li server.workspace.remove_text_document(client_uri) +class TestAgentHost: + """Claude Code support: freshness markers for the PostToolUse hook, didSave after disk writes.""" + + @pytest.fixture + def marker(self, monkeypatch: pytest.MonkeyPatch) -> MagicMock: + written = MagicMock() + monkeypatch.setattr(srv_mod, "write_marker", written) + monkeypatch.setattr(server, "_agent_host", True) + return written + + async def test_marker_on_final_publish_not_custom_first(self, live: MagicMock, marker: MagicMock) -> None: + server._hold_mode = _HOLD_CUSTOM_FIRST + await _edit() + await _until(lambda: live.call_count == 1) + marker.assert_not_called() # custom-only publish is not final + await _past_min_age() + _jdtls_publishes([]) + await _until(lambda: live.call_count == 2) + marker.assert_called_once_with("/mod/src/Foo.java", content_digest(SOURCE.encode())) + + async def test_background_republish_of_unedited_file_writes_no_marker( + self, live: MagicMock, marker: MagicMock + ) -> None: + _jdtls_publishes([_java_diag("x")]) # untracked jdtls republish, no edit since the last marker + assert live.call_count == 1 + marker.assert_not_called() + + async def test_one_marker_per_edit(self, live: MagicMock, marker: MagicMock) -> None: + await _edit() + await _past_min_age() + _jdtls_publishes([]) + await _until(lambda: live.call_count == 1) + _jdtls_publishes([_java_diag("later cycle")]) + assert marker.call_count == 1 + + async def test_off_mode_debounce_publish_is_not_final(self, live: MagicMock, marker: MagicMock) -> None: + server._hold_mode = _HOLD_OFF + _jdtls_publishes([_java_diag("stale")]) + await _edit() + await _until(lambda: live.call_count == 2) + marker.assert_not_called() # it carries the previous edit's jdtls set + _jdtls_publishes([]) + marker.assert_called_once() + + async def test_unheld_change_publish_is_final(self, live: MagicMock, marker: MagicMock) -> None: + server._proxy.modules.clear() # module not imported: not held, nothing fresher is coming + await _edit() + await _until(lambda: live.call_count == 1) + marker.assert_called_once() + + async def test_did_open_writes_placeholder(self, live: MagicMock, marker: MagicMock) -> None: + with patch.object(server._proxy, "add_module_if_new", AsyncMock()): + await on_did_open( + lsp.DidOpenTextDocumentParams( + text_document=lsp.TextDocumentItem(uri=URI, language_id="java", version=1, text=SOURCE) + ) + ) + marker.assert_called_once_with("/mod/src/Foo.java", OPENING) # the open's own publish isn't final + assert live.call_count == 1 + _jdtls_publishes([]) + assert marker.call_count == 2 + + async def test_no_marker_for_other_clients(self, live: MagicMock, monkeypatch: pytest.MonkeyPatch) -> None: + written = MagicMock() + monkeypatch.setattr(srv_mod, "write_marker", written) + await _edit() + await _past_min_age() + _jdtls_publishes([]) + await _until(lambda: live.call_count == 1) + written.assert_not_called() + + @pytest.mark.usefixtures("live", "marker") + @pytest.mark.parametrize( + ("on_disk", "expect_save"), + [(SOURCE, True), (SOURCE + "// newer", False), (SOURCE.replace("null", "NULL"), False), (None, False)], + ids=["same", "longer", "same-size-different", "missing"], + ) + async def test_did_save_forwarded_only_when_buffer_matches_disk( + self, tmp_path: Path, on_disk: str | None, expect_save: bool + ) -> None: + java = tmp_path / "Disk.java" + if on_disk is not None: + java.write_text(on_disk) + uri = java.as_uri() + _put_document(uri) + try: + await _edit(uri) + await _past_debounce() + sent = server._proxy.send_notification + assert isinstance(sent, AsyncMock) + methods = [call.args[0] for call in sent.call_args_list] + assert methods[0] == "textDocument/didChange" + assert ("textDocument/didSave" in methods) is expect_save + finally: + task = srv_mod._pending.pop(uri, None) + if task is not None: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + server._session_opened_uris.pop(srv_mod._normalize_uri(uri), None) + server.workspace.remove_text_document(uri) + + @pytest.mark.usefixtures("live", "marker") + async def test_no_did_save_when_jdtls_not_running(self, monkeypatch: pytest.MonkeyPatch) -> None: + forward_save = MagicMock() + monkeypatch.setattr(srv_mod, "_forward_save_if_on_disk", forward_save) + server._proxy._available = False + await _edit() + forward_save.assert_not_called() + + @pytest.mark.usefixtures("live", "marker") + async def test_did_save_kill_switch(self, monkeypatch: pytest.MonkeyPatch) -> None: + forward_save = MagicMock() + monkeypatch.setattr(srv_mod, "_forward_save_if_on_disk", forward_save) + monkeypatch.setenv("JAVA_FUNCTIONAL_LSP_AGENT_DIDSAVE", "off") + await _edit() + forward_save.assert_not_called() + + @pytest.mark.usefixtures("live", "marker") + async def test_did_save_check_failure_keeps_hold(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(srv_mod, "to_fs_path", MagicMock(side_effect=UnicodeEncodeError("utf-8", "", 0, 1, "x"))) + await _edit() + assert srv_mod._freshness.is_pending(URI) + assert URI in srv_mod._pending + + @pytest.mark.usefixtures("live") + async def test_ide_clients_do_not_read_disk_on_change(self, monkeypatch: pytest.MonkeyPatch) -> None: + forward_save = MagicMock() + monkeypatch.setattr(srv_mod, "_forward_save_if_on_disk", forward_save) + await _edit() + forward_save.assert_not_called() + + @pytest.mark.parametrize( + ("client", "agent"), [("Claude Code", True), ("Visual Studio Code", False), ("Neovim", False), ("", False)] + ) + def test_agent_host_detection(self, client: str, agent: bool) -> None: + assert srv_mod._is_agent_host(client) is agent + + # --- Proxy additions --- diff --git a/tests/test_e2e_cross_file.py b/tests/test_e2e_cross_file.py index 5abb91f..810dcb9 100644 --- a/tests/test_e2e_cross_file.py +++ b/tests/test_e2e_cross_file.py @@ -4,7 +4,8 @@ parameter, then ``Caller``'s call site is updated, both written to disk like an agent's Edit tool does. With didSave jdtls converges every time; without it, in roughly 2 of 5 runs jdtls's only post-edit publish for Caller still reports the old arity and is never -corrected (xfail, non-strict — the wrapper-side fix is tracked as #109 Part B). +corrected (opt-in measurement). The server therefore forwards a didSave after agent edits; +tests/test_e2e_hold.py covers that end to end. """ from __future__ import annotations diff --git a/tests/test_e2e_hold.py b/tests/test_e2e_hold.py index eb9a471..5390167 100644 --- a/tests/test_e2e_hold.py +++ b/tests/test_e2e_hold.py @@ -1,17 +1,22 @@ """E2E through the real server + real jdtls with default hold constants (#109). -Opens a Maven project where ``Foo`` references ``q.Bar`` without importing it, waits -for jdtls to report "Bar cannot be resolved", then adds the import. With the hold -(``custom-first``, what Claude Code gets) no publish after the fix may still carry the -resolved error; with ``off`` the previous behavior re-publishes it at the debounce. +Maven projects driven the way Claude Code drives the server (client name "Claude Code", +files written to disk before didChange, no didSave): + +- fixing a missing import never re-publishes the resolved error (vs ``off``: it does); +- the PostToolUse hook returns only after the fresh jdtls set was published; +- a cross-file constructor-arity change converges without a client didSave. """ from __future__ import annotations import asyncio +import json import os import shutil +import subprocess import sys +from collections.abc import Callable from pathlib import Path import pytest @@ -26,6 +31,7 @@ pytest.mark.skipif(find_jdtls_java_home() is None, reason="no Java 21+ found"), ] +HOOK = Path(__file__).parent.parent / "hooks" / "post_tool_lint.py" _POM = """\ 4.0.0 @@ -41,62 +47,104 @@ _BAR = "package q;\n\npublic class Bar {}\n" _FOO_BROKEN = "package p;\n\npublic class Foo {\n Bar bar;\n}\n" _FOO_FIXED = "package p;\n\nimport q.Bar;\n\npublic class Foo {\n Bar bar;\n}\n" +_FOO_FIXED_NEW_ERROR = 'package p;\n\nimport q.Bar;\n\npublic class Foo {\n Bar bar;\n int n = "s";\n}\n' _UNRESOLVED = "Bar cannot be resolved" +_TYPE_MISMATCH = "Type mismatch" _READY_TIMEOUT_SEC = 150 _OBSERVE_SEC = 8.0 +_QUIET_SEC = 4.0 +_CONVERGE_TIMEOUT_SEC = 30 + + +def _messages(diags: list[lsp.Diagnostic]) -> list[str]: + return [d.message for d in diags] + + +def _errors(diags: list[lsp.Diagnostic]) -> list[str]: + return [d.message for d in diags if d.severity == lsp.DiagnosticSeverity.Error] + +def _has(diags: list[lsp.Diagnostic], text: str) -> bool: + return any(text in m for m in _messages(diags)) -def _has_unresolved(diags: list[lsp.Diagnostic]) -> bool: - return any(_UNRESOLVED in d.message for d in diags) +def _foo(n: int) -> str: + params = ", ".join(f"int a{i}" for i in range(n)) + return f"package p;\n\npublic class Foo {{\n public Foo({params}) {{}}\n}}\n" -def _write_project(root: Path) -> Path: + +def _caller(n: int) -> str: + args = ", ".join(str(i) for i in range(n)) + return f"package p;\n\npublic class Caller {{\n Foo make() {{\n return new Foo({args});\n }}\n}}\n" + + +def _write_project(root: Path, files: dict[str, str]) -> dict[str, Path]: (root / "pom.xml").write_text(_POM) - src = root / "src" / "main" / "java" - (src / "p").mkdir(parents=True) - (src / "q").mkdir(parents=True) - (src / "q" / "Bar.java").write_text(_BAR) - foo = src / "p" / "Foo.java" - foo.write_text(_FOO_BROKEN) - return foo + paths: dict[str, Path] = {} + for rel, text in files.items(): + path = root / "src" / "main" / "java" / rel + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + paths[rel] = path + return paths -class _FooWatch: - """Records every publish the server sends for Foo.""" +class _PublishWatch: + """Records every publish the server sends, per URI.""" - def __init__(self, foo_uri: str) -> None: - self.foo_uri = foo_uri - self.history: list[list[lsp.Diagnostic]] = [] - self.arrived = asyncio.Event() + def __init__(self) -> None: + self.history: dict[str, list[list[lsp.Diagnostic]]] = {} + self.arrived: dict[str, asyncio.Event] = {} def on_publish(self, params: lsp.PublishDiagnosticsParams) -> None: - if params.uri == self.foo_uri: - self.history.append(list(params.diagnostics)) - self.arrived.set() + self.history.setdefault(params.uri, []).append(list(params.diagnostics)) + self.arrived.setdefault(params.uri, asyncio.Event()).set() + + def latest(self, uri: str) -> list[lsp.Diagnostic]: + return self.history.get(uri, [[]])[-1] + + async def _next(self, uri: str, timeout: float) -> bool: + event = self.arrived.setdefault(uri, asyncio.Event()) + event.clear() + try: + await asyncio.wait_for(event.wait(), timeout=timeout) + except asyncio.TimeoutError: + return False + return True - async def wait_unresolved(self) -> bool: - deadline = asyncio.get_running_loop().time() + _READY_TIMEOUT_SEC - while not (self.history and _has_unresolved(self.history[-1])): + async def wait_for(self, uri: str, predicate: Callable[[list[lsp.Diagnostic]], bool], timeout: float) -> bool: + deadline = asyncio.get_running_loop().time() + timeout + while not (self.history.get(uri) and predicate(self.latest(uri))): remaining = deadline - asyncio.get_running_loop().time() - if remaining <= 0: - return False - self.arrived.clear() - try: - await asyncio.wait_for(self.arrived.wait(), timeout=remaining) - except asyncio.TimeoutError: + if remaining <= 0 or not await self._next(uri, remaining): return False return True + async def wait_quiet(self, uri: str, since: int) -> bool: + """Wait until *uri* published at least once after index *since*, then stayed quiet.""" + deadline = asyncio.get_running_loop().time() + _CONVERGE_TIMEOUT_SEC + while asyncio.get_running_loop().time() < deadline: + if not await self._next(uri, _QUIET_SEC) and len(self.history.get(uri, [])) > since: + return True + return False + -async def _start_server(root: Path, mode: str, watch: _FooWatch) -> LanguageClient: +async def _start_server(root: Path, watch: _PublishWatch, markers: Path, **env: str) -> LanguageClient: + """Start the server as Claude Code; markers go to a private TMPDIR, never the user's real one.""" client = LanguageClient("e2e-hold", "1.0") def on_publish(params: lsp.PublishDiagnosticsParams) -> None: # pygls needs a plain function watch.on_publish(params) client.feature(lsp.TEXT_DOCUMENT_PUBLISH_DIAGNOSTICS)(on_publish) - env = {**os.environ, "JAVA_FUNCTIONAL_LSP_DIAG_HOLD": mode} - await client.start_io(sys.executable, "-m", "java_functional_lsp", env=env) + server_env = { + **os.environ, + "TMPDIR": str(markers), + "JAVA_FUNCTIONAL_LSP_DIAG_HOLD": "custom-first", + "JAVA_FUNCTIONAL_LSP_AGENT_DIDSAVE": "on", + **env, + } + await client.start_io(sys.executable, "-m", "java_functional_lsp", env=server_env) await client.initialize_async( lsp.InitializeParams( process_id=os.getpid(), @@ -121,39 +169,126 @@ async def _stop_server(client: LanguageClient) -> None: pass +def _open(client: LanguageClient, path: Path) -> None: + client.text_document_did_open( + lsp.DidOpenTextDocumentParams( + text_document=lsp.TextDocumentItem(uri=path.as_uri(), language_id="java", version=1, text=path.read_text()) + ) + ) + + +def _agent_edit(client: LanguageClient, path: Path, text: str, version: int) -> None: + """Like Claude Code's Edit tool: write the file, then didChange (no didSave).""" + path.write_text(text) + client.text_document_did_change( + lsp.DidChangeTextDocumentParams( + text_document=lsp.VersionedTextDocumentIdentifier(uri=path.as_uri(), version=version), + content_changes=[lsp.TextDocumentContentChangeWholeDocument(text=text)], + ) + ) + + +def _run_hook(path: Path, tmpdir: Path) -> int: + proc = subprocess.run( + [sys.executable, str(HOOK)], + input=json.dumps({"tool_input": {"file_path": str(path)}}), + capture_output=True, + text=True, + timeout=30, + check=False, + env={**os.environ, "TMPDIR": str(tmpdir), "JAVA_FUNCTIONAL_LSP_HOOK_WAIT": "4"}, + ) + return proc.returncode + + +def _markers(tmp_path: Path) -> Path: + markers = tmp_path / "tmp" + markers.mkdir() + return markers + + @pytest.mark.timeout(_READY_TIMEOUT_SEC + 60) @pytest.mark.parametrize("mode", ["custom-first", "off"]) async def test_fixing_import_never_republishes_resolved_error(tmp_path: Path, mode: str) -> None: - foo = _write_project(tmp_path) - foo_uri = foo.as_uri() - watch = _FooWatch(foo_uri) - client = await _start_server(tmp_path, mode, watch) + markers = _markers(tmp_path) + foo = _write_project(tmp_path, {"q/Bar.java": _BAR, "p/Foo.java": _FOO_BROKEN})["p/Foo.java"] + uri = foo.as_uri() + watch = _PublishWatch() + client = await _start_server(tmp_path, watch, markers, JAVA_FUNCTIONAL_LSP_DIAG_HOLD=mode) try: - client.text_document_did_open( - lsp.DidOpenTextDocumentParams( - text_document=lsp.TextDocumentItem(uri=foo_uri, language_id="java", version=1, text=_FOO_BROKEN) - ) - ) - if not await watch.wait_unresolved(): + _open(client, foo) + if not await watch.wait_for(uri, lambda d: _has(d, _UNRESOLVED), _READY_TIMEOUT_SEC): pytest.skip("jdtls did not report the unresolved type in time (project import too slow)") - - history = watch.history - before_fix = len(history) - foo.write_text(_FOO_FIXED) - client.text_document_did_change( - lsp.DidChangeTextDocumentParams( - text_document=lsp.VersionedTextDocumentIdentifier(uri=foo_uri, version=2), - content_changes=[lsp.TextDocumentContentChangeWholeDocument(text=_FOO_FIXED)], - ) - ) + before_fix = len(watch.history[uri]) + _agent_edit(client, foo, _FOO_FIXED, 2) await asyncio.sleep(_OBSERVE_SEC) - after_fix = history[before_fix:] + after_fix = watch.history[uri][before_fix:] assert after_fix, "server published nothing after the fix" - stale = [i for i, diags in enumerate(after_fix) if _has_unresolved(diags)] + stale = [i for i, diags in enumerate(after_fix) if _has(diags, _UNRESOLVED)] if mode == "off": assert stale, "expected the pre-fix behavior to re-publish the resolved error" else: assert not stale, f"publishes {stale} after the fix still carried '{_UNRESOLVED}'" - assert not _has_unresolved(after_fix[-1]) + assert not _has(after_fix[-1], _UNRESOLVED) + finally: + await _stop_server(client) + + +@pytest.mark.timeout(_READY_TIMEOUT_SEC + 60) +async def test_hook_returns_after_fresh_jdtls_publish(tmp_path: Path) -> None: + """When the PostToolUse hook returns, the client already holds jdtls's result for the edit.""" + markers = _markers(tmp_path) + foo = _write_project(tmp_path, {"q/Bar.java": _BAR, "p/Foo.java": _FOO_BROKEN})["p/Foo.java"] + uri = foo.as_uri() + watch = _PublishWatch() + client = await _start_server(tmp_path, watch, markers) + try: + _open(client, foo) + if not await watch.wait_for(uri, lambda d: _has(d, _UNRESOLVED), _READY_TIMEOUT_SEC): + pytest.skip("jdtls did not report the unresolved type in time (project import too slow)") + _agent_edit(client, foo, _FOO_FIXED_NEW_ERROR, 2) + if _has(watch.latest(uri), _TYPE_MISMATCH): + pytest.skip("inconclusive: jdtls answered before the hook started") + assert await asyncio.to_thread(_run_hook, foo, markers) == 0 + await asyncio.sleep(0.1) # let the client read what the server sent before the hook returned + latest = watch.latest(uri) + assert not _has(latest, _UNRESOLVED), _messages(latest) + assert _has(latest, _TYPE_MISMATCH), f"jdtls's new error missing when the hook returned: {_messages(latest)}" + finally: + await _stop_server(client) + + +@pytest.mark.timeout(_READY_TIMEOUT_SEC + 3 * _CONVERGE_TIMEOUT_SEC + 60) +async def test_cross_file_arity_change_converges_without_client_did_save(tmp_path: Path) -> None: + """Without didSave jdtls left Caller stale in ~2/5 runs; the server now sends it (three cycles). + + hold-all so every publish carries jdtls results (custom-first's custom-only publish has + no jdtls errors and could satisfy the check early). This is a smoke test: the stale case + is nondeterministic, and with JAVA_FUNCTIONAL_LSP_AGENT_DIDSAVE=off it failed in only some + manual runs. The didSave effect itself is measured in tests/test_e2e_cross_file.py. + """ + markers = _markers(tmp_path) + paths = _write_project(tmp_path, {"p/Foo.java": _foo(2), "p/Caller.java": _caller(1)}) + foo, caller = paths["p/Foo.java"], paths["p/Caller.java"] + caller_uri = caller.as_uri() + watch = _PublishWatch() + client = await _start_server(tmp_path, watch, markers, JAVA_FUNCTIONAL_LSP_DIAG_HOLD="hold-all") + try: + _open(client, foo) + _open(client, caller) + # Caller starts with the wrong arity: only a project-mode jdtls reports that. + if not await watch.wait_for(caller_uri, lambda d: bool(_errors(d)), _READY_TIMEOUT_SEC): + pytest.skip("jdtls did not import the Maven project in time") + version = 2 + _agent_edit(client, caller, _caller(2), version) + assert await watch.wait_for(caller_uri, lambda d: not _errors(d), _CONVERGE_TIMEOUT_SEC) + for arity in (3, 4, 5): + version += 1 + since = len(watch.history[caller_uri]) + _agent_edit(client, foo, _foo(arity), version) + _agent_edit(client, caller, _caller(arity), version) + assert await watch.wait_quiet(caller_uri, since), f"arity {arity}: Caller never published or settled" + published = [_errors(d) for d in watch.history[caller_uri][since:]] + assert not _errors(watch.latest(caller_uri)), f"arity {arity}: Caller publishes after the edit: {published}" finally: await _stop_server(client) diff --git a/tests/test_freshness_marker.py b/tests/test_freshness_marker.py new file mode 100644 index 0000000..ba2fa6b --- /dev/null +++ b/tests/test_freshness_marker.py @@ -0,0 +1,243 @@ +"""Tests for the freshness markers shared by the server and the PostToolUse hook (#109).""" + +from __future__ import annotations + +import getpass +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import threading +import time +from collections.abc import Iterator +from pathlib import Path +from types import ModuleType +from typing import Any + +import pytest + +from java_functional_lsp import freshness_marker + +HOOK = Path(__file__).parent.parent / "hooks" / "post_tool_lint.py" +CLEAN_JAVA = "public class Clean {}\n" +DEAD_PID = 2**22 + 12345 # above the hard pid limit on Linux (PID_MAX_LIMIT 2**22) and macOS (99999) + + +def _load_hook() -> ModuleType: + spec = importlib.util.spec_from_file_location("post_tool_lint", HOOK) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.fixture +def private_tmp(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]: + monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) + freshness_marker._validated.clear() + yield tmp_path + freshness_marker._validated.clear() + + +def _digest_of(path: Path) -> str: + return freshness_marker.content_digest(path.read_bytes()) + + +def _stamp(java: Path, digest: str, pid: int | None = None) -> None: + """Write a marker the way the server does (tempfile.tempdir must point at the test dir).""" + if pid is None: + freshness_marker.write_marker(str(java), digest) + return + marker = freshness_marker.marker_path(str(java)) + marker.write_text(f"{pid} {digest}") + + +def _run_hook(file_path: Path, tmpdir: Path, wait: str = "3") -> tuple[subprocess.CompletedProcess[str], float]: + started = time.monotonic() + proc = subprocess.run( + [sys.executable, str(HOOK)], + input=json.dumps({"tool_input": {"file_path": str(file_path)}}), + capture_output=True, + text=True, + timeout=30, + check=False, + env={**os.environ, "TMPDIR": str(tmpdir), "JAVA_FUNCTIONAL_LSP_HOOK_WAIT": wait}, + ) + return proc, time.monotonic() - started + + +class TestMarker: + def test_hook_and_server_agree_on_marker_path(self, private_tmp: Path) -> None: + java = private_tmp / "A.java" + assert _load_hook()._marker_path(str(java)) == freshness_marker.marker_path(str(java)) + + def test_user_fallback_matches_when_getpass_fails(self, private_tmp: Path, monkeypatch: pytest.MonkeyPatch) -> None: + def no_user() -> str: + raise KeyError("no passwd entry") + + monkeypatch.setattr(getpass, "getuser", no_user) + java = private_tmp / "A.java" + assert _load_hook()._marker_path(str(java)) == freshness_marker.marker_path(str(java)) + assert str(os.getuid()) in str(freshness_marker.marker_dir()) + + def test_write_marker_records_pid_and_digest_privately(self, private_tmp: Path) -> None: + java = private_tmp / "A.java" + freshness_marker.write_marker(str(java), "abc123") + marker = freshness_marker.marker_path(str(java)) + assert marker.read_text() == f"{os.getpid()} abc123" + assert marker.stat().st_mode & 0o777 == 0o600 + assert marker.parent.stat().st_mode & 0o777 == 0o700 + assert _load_hook()._read_marker(marker) == (os.getpid(), "abc123") + + @pytest.mark.parametrize("level", ["base", "fresh"]) + def test_symlinked_marker_dir_is_refused(self, private_tmp: Path, level: str) -> None: + elsewhere = private_tmp / "elsewhere" + elsewhere.mkdir() + directory = freshness_marker.marker_dir() + if level == "base": + directory.parent.symlink_to(elsewhere) + else: + directory.parent.mkdir(mode=0o700) + directory.symlink_to(elsewhere) + freshness_marker.write_marker(str(private_tmp / "A.java"), "abc") + assert not any(elsewhere.rglob("*")) + + def test_loose_permissions_are_tightened(self, private_tmp: Path) -> None: + base = freshness_marker.marker_dir().parent + base.mkdir(mode=0o755) + base.chmod(0o755) + freshness_marker.write_marker(str(private_tmp / "A.java"), "abc") + assert base.stat().st_mode & 0o777 == 0o700 + + def test_write_marker_never_raises(self, private_tmp: Path) -> None: + freshness_marker.marker_dir().parent.write_text("not a directory") + freshness_marker.write_marker(str(private_tmp / "A.java"), "abc") + assert not freshness_marker.marker_dir().exists() + + @pytest.mark.parametrize("content", ["", "garbage", "1 2 3", "notapid abc", "0 abc", "-1 abc"]) + def test_hook_rejects_malformed_marker(self, private_tmp: Path, content: str) -> None: + java = private_tmp / "A.java" + freshness_marker.write_marker(str(java), "abc") + marker = freshness_marker.marker_path(str(java)) + marker.write_text(content) + assert _load_hook()._read_marker(marker) is None + + def test_hook_rejects_loose_marker_dir(self, private_tmp: Path) -> None: + java = private_tmp / "A.java" + freshness_marker.write_marker(str(java), "abc") + freshness_marker.marker_dir().chmod(0o777) + assert _load_hook()._read_marker(freshness_marker.marker_path(str(java))) is None + + def test_hook_does_not_follow_marker_symlink(self, private_tmp: Path) -> None: + java = private_tmp / "A.java" + freshness_marker.write_marker(str(java), "abc") + marker = freshness_marker.marker_path(str(java)) + target = private_tmp / "planted" + target.write_text(f"{os.getpid()} abc") + marker.unlink() + marker.symlink_to(target) + assert _load_hook()._read_marker(marker) is None + + +class TestHookWait: + """_wait_for_fresh_diagnostics in-process: real time, small budgets.""" + + def _java(self, root: Path, text: str = CLEAN_JAVA) -> Path: + java = root / "Clean.java" + java.write_text(text) + return java + + def _timed_wait(self, java: Path, budget: float, monkeypatch: pytest.MonkeyPatch, wait: str = "4") -> float: + monkeypatch.setenv("JAVA_FUNCTIONAL_LSP_HOOK_WAIT", wait) + started = time.monotonic() + _load_hook()._wait_for_fresh_diagnostics(java, budget=budget) + return time.monotonic() - started + + def test_returns_when_digest_matches(self, private_tmp: Path, monkeypatch: pytest.MonkeyPatch) -> None: + java = self._java(private_tmp) + _stamp(java, "previous-version") + timer = threading.Timer(0.3, lambda: _stamp(java, _digest_of(java))) + timer.start() + try: + elapsed = self._timed_wait(java, budget=3.0, monkeypatch=monkeypatch) + finally: + timer.cancel() + assert 0.25 <= elapsed < 2.0 + + def test_already_matching_returns_at_once(self, private_tmp: Path, monkeypatch: pytest.MonkeyPatch) -> None: + java = self._java(private_tmp) + _stamp(java, _digest_of(java)) + assert self._timed_wait(java, budget=3.0, monkeypatch=monkeypatch) < 0.2 + + def test_no_marker_means_no_wait(self, private_tmp: Path, monkeypatch: pytest.MonkeyPatch) -> None: + assert self._timed_wait(self._java(private_tmp), budget=3.0, monkeypatch=monkeypatch) < 0.2 + + def test_dead_server_means_no_wait(self, private_tmp: Path, monkeypatch: pytest.MonkeyPatch) -> None: + java = self._java(private_tmp) + _stamp(java, "previous-version") # creates the private dirs + _stamp(java, "previous-version", pid=DEAD_PID) + assert self._timed_wait(java, budget=3.0, monkeypatch=monkeypatch) < 0.2 + + def test_opening_placeholder_waits(self, private_tmp: Path, monkeypatch: pytest.MonkeyPatch) -> None: + java = self._java(private_tmp) + _stamp(java, freshness_marker.OPENING) + elapsed = self._timed_wait(java, budget=0.3, monkeypatch=monkeypatch) + assert 0.25 <= elapsed < 1.0 + + @pytest.mark.parametrize(("budget", "wait", "low", "high"), [(0.3, "4", 0.25, 1.0), (4.0, "0.3", 0.25, 1.0)]) + def test_wait_bounded_by_budget_and_setting( + self, private_tmp: Path, monkeypatch: pytest.MonkeyPatch, budget: float, wait: str, low: float, high: float + ) -> None: + java = self._java(private_tmp) + _stamp(java, "previous-version") + assert low <= self._timed_wait(java, budget=budget, monkeypatch=monkeypatch, wait=wait) < high + + @pytest.mark.parametrize("budget", [0.0, -1.0]) + def test_exhausted_budget_returns_immediately( + self, private_tmp: Path, monkeypatch: pytest.MonkeyPatch, budget: float + ) -> None: + java = self._java(private_tmp) + _stamp(java, "previous-version") + assert self._timed_wait(java, budget=budget, monkeypatch=monkeypatch) < 0.2 + + @pytest.mark.parametrize(("value", "expected"), [("1.5", 1.5), ("-1", 0.0), ("99", 4.0), ("soon", 3.0)]) + def test_wait_seconds_parsing(self, monkeypatch: pytest.MonkeyPatch, value: str, expected: float) -> None: + monkeypatch.setenv("JAVA_FUNCTIONAL_LSP_HOOK_WAIT", value) + assert _load_hook()._fresh_wait_seconds() == expected + + +class TestHookSubprocess: + """Smoke tests of the hook as Claude Code runs it.""" + + def test_waits_for_matching_digest(self, private_tmp: Path) -> None: + java = private_tmp / "Clean.java" + java.write_text(CLEAN_JAVA) + _stamp(java, "previous-version") + timer = threading.Timer(1.0, lambda: _stamp(java, _digest_of(java))) + timer.start() + try: + proc, elapsed = _run_hook(java, private_tmp) + finally: + timer.cancel() + assert proc.returncode == 0 + assert 0.95 <= elapsed < 3.0 + + def test_violations_still_reported_after_wait(self, private_tmp: Path) -> None: + java = private_tmp / "Bad.java" + java.write_text("public class Bad { String f() { return null; } }\n") + _stamp(java, "previous-version") + proc, _ = _run_hook(java, private_tmp, wait="0.3") + assert proc.returncode == 0 + out: dict[str, Any] = json.loads(proc.stdout) + assert "null-return" in out["hookSpecificOutput"]["additionalContext"] + + def test_broken_marker_dir_never_suppresses_lint_output(self, private_tmp: Path) -> None: + java = private_tmp / "Bad.java" + java.write_text("public class Bad { String f() { return null; } }\n") + freshness_marker.marker_dir().parent.write_text("not a directory") + proc, _ = _run_hook(java, private_tmp) + assert proc.returncode == 0 + assert "null-return" in json.loads(proc.stdout)["hookSpecificOutput"]["additionalContext"] diff --git a/uv.lock b/uv.lock index c669b5e..769f2fc 100644 --- a/uv.lock +++ b/uv.lock @@ -184,7 +184,7 @@ wheels = [ [[package]] name = "java-functional-lsp" -version = "0.12.1" +version = "0.13.0" source = { editable = "." } dependencies = [ { name = "pygls" },